-4

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"]

jibin george
  • 121
  • 6

5 Answers5

2

Use concat instead of push to combine arrays with each other.

var nameArr = timeBeenSelected.toString();
console.log(nameArr);
var nameArr2 = timeBeenSelected.split(',');
console.log(nameArr2);
console.log(nameArr2.concat(result));
SparkFountain
  • 2,110
  • 15
  • 35
2

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

Sourabh Somani
  • 2,138
  • 1
  • 13
  • 27
2
array1 = ['a', 'b'];
array2 = ['c', 'd'];

classic js: Just concat two arrays.

array1.concat(array2)

es6: you can take a glance destructering example:

unifyArr = [...array1, ...array2]
isik_hi
  • 89
  • 5
1

Using ES6, you can concatenate 2 arrays by

let newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
let result = ["10:00","16:00"]
let combined = [..newArray,..result];
deepak thomas
  • 1,118
  • 9
  • 23
1

You can merge both arrays using spread operator , Check the below snippet

var newArray = ['11:30', '12:00','12:30', '13:00' ,'13:30', '14:00'];
var result = ["10:00","16:00"]

var output = [...newArray, ...result] //without mutating the input arrays 

console.log(output) // total 8 elements
Learner
  • 8,379
  • 7
  • 44
  • 82