rd22
rd22

Reputation: 1032

How to add(copy) an array content to another array in javascript without replacing the content of the array?

How do I copy contents of an array to another array.

I have 2 arrays foo and bar, please have a look below:

foo = []   //this is a temp array which will be generated in a loop
bar = []

for(someCondition){
  for(someOtherCondition){
     foo = assignSomething;
  }
  // here I want the content of foo to be added to bar array and keep appending to the existing array
  //I tried bar.push(foo)  but this just creates an array of foo's but doesn't copy the foo array into bar array.
  //I also tried bar = foo.slice() but this just replaces the bar array everytime with new data
    }

Thanks for the help.

Upvotes: 1

Views: 108

Answers (1)

OddDev
OddDev

Reputation: 3734

You may want to use the concat() method of Array's prototype.

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/concat

var alpha = ['a', 'b', 'c'],
    numeric = [1, 2, 3];

var alphaNumeric = alpha.concat(numeric);

console.log(alphaNumeric);

Browser compatibility

    Desktop Mobile 

Feature     Chrome  Firefox (Gecko)     Internet Explorer   Opera   Safari
Basic support   1.0     1.0 (1.7 or earlier)    5.5     (Yes)   (Yes)

Upvotes: 2

Related Questions