0

for example if I have two arrys
arr1[10,20,30]
arr2[40,50,60]
can I get help on how to merge them to get arr1[10,20,30,40,50,60]

4
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by scrappedcola
0

Like many things in coding, there are a couple approaches. The simplest is to just use the JS built in function concat.

var newArray = arr1.concat(arr2);

Another approach (and less efficient) would be to loop through the second array and push each element onto the first using

arr1.push(arr2[i])

.
There is yet a third option that would apply if you needed to keep distinct values where you would loop through the both arrays and compare values and then either push the value onto a new array or one of the originals.

0

The above syntax is absolutely correct that what scrappedcola provided. If you working with multiple arrays you can also use this below syntax

var a=new Array('a','b','c');
var b=new Array('d','e','f');
var d=new Array('x','y','z');
var c=a.concat(b,d);
0

I hope that your 'merge' definition means 'concatenate'. If your meaning of merge is similar to set union, concatenate won't do it. Just want to make sure.

There is yet a third option that would apply if you needed to keep distinct values where you would loop through the both arrays and compare values and then either push the value onto a new array or one of the originals.

That's the idea for set union, but you don't need to loop through both arrays. You need to loop through only 1 array, and use indexOf() function in another array to check whether the element exists in the array. Example code snippet is below...

var a = [1,2,3,4,5,6]
var b = [4,5,6,7,8]

for (var i=0; i<b.length; i++) {
  if (a.indexOf(b[i])<0) {  // element doesn't exist inside 'a' array
    a.push(b[i])
  }
}
// result is a = [1,2,3,4,5,6,7,8]
//           b = [4,5,6,7,8]

Edited by Taywin: n/a

0

You need to loop through only 1 array, and use indexOf() function in another array to check whether the element exists in the array.

indexOf may work fine in FF but IE does not currently support indexOf on Arrays and since the OP didn't state which browser I was suggesting cross browser.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.