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]

Recommended Answers

All 4 Replies

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.

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);

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]

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.