Search code examples
javascriptarrayspusharr

Join two arrays in to one - Javascript


I am trying to merge arrays in to one.

var newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
result = ["10:00","16:00"];   // this is coming from my db

When i try to merge them i get 7 not sure why

var nameArr = timeBeenSelected.toString();
console.log(nameArr);
var nameArr2 = timeBeenSelected.split(',');
console.log(nameArr2);
console.log(newArray.push(result));

console.log(result); ["10:00","16:00"]

console.log(newArray); (6) ["11:30", "12:00", "12:30", "13:00", "13:30", "14:00"]


Solution

  • Here is the solution

    var newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
    var result = ["10:00","16:00"]// Make sure whatever the data you are getting it should be JSON
    //If it is in string just convert your result like as follows
    //result=JSON.parse(result)
    
    var finalResult = [...new Set([...newArray,...result])].sort()
    console.log(finalResult)

    Code Explanation

    [...newArray,...result]//This will return joined array
    

    Above array can be duplicate results So I am using new Set() to get unique values.

    [...new Set([...newArray,...result])]
    

    Now finally sorting the value using sort() function which is optional