-1

I want to add mongo ids in a final array from my query, here is what i am trying to do

var arr = [];

// array1 =  [ "59ae3b20a8473d45d11987f8",
 "59bb8a9c8f541e060054580e",
  "59ae905f43d38f64d85d3c21"]
//array2 =  [ 
  "59bce938cbe9c90271742c1a",
  "59bcebb4cbe9c90271742c2e" ]

and when i am adding them as arr.push(array1), arr.push(array2) then i am getting this result

//arr = [ 59ae3b20a8473d45d11987f8,
  59bb8a9c8f541e060054580e,
  59ae905f43d38f64d85d3c21,
  59bce938cbe9c90271742c1a,
  59bcebb4cbe9c90271742c2e ]

in result array the type has changed(from strings) and i want these elements as string as they are in array1 and array2, i tried using concat but not working, please help

ewcz
  • 12,819
  • 1
  • 25
  • 47
ankitkhandelwal185
  • 1,023
  • 1
  • 15
  • 24
  • Use [concat()](https://www.w3schools.com/jsref/jsref_concat_array.asp) method instead... `array1.concat(array2)` – Ashh Jun 22 '18 at 07:57
  • 1
    also note that `concat` in contrast to `push` does not mutate the original array, it returns a copy instead. Alternatively, you might use `[...array1, ...array2]` – ewcz Jun 22 '18 at 08:20

2 Answers2

1

Using the concat method, you could proceed as:

arr = [].concat(array1, array2)

or even just arr = array1.concat(array2). Here, the result is assigned to arr since concat does not mutate the original array.

Alternatively, using the spread syntax:

arr = [...array1, ...array2]
ewcz
  • 12,819
  • 1
  • 25
  • 47
0

array1 =  [ "59ae3b20a8473d45d11987f8",
 "59bb8a9c8f541e060054580e",
  "59ae905f43d38f64d85d3c21"]
array2 =  [ 
  "59bce938cbe9c90271742c1a",
  "59bcebb4cbe9c90271742c2e" ]
var finalArr = array1.concat(array2);
console.log(finalArr);

array1 =  [ "59ae3b20a8473d45d11987f8",
 "59bb8a9c8f541e060054580e",
  "59ae905f43d38f64d85d3c21"]
array2 =  [ 
  "59bce938cbe9c90271742c1a",
  "59bcebb4cbe9c90271742c2e" ]
var finalArr = [...new Set([...array1 ,...array2])];
console.log(finalArr);
Parth Raval
  • 4,097
  • 3
  • 23
  • 36