1

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.

2
  • 4
    JavaScript Array concat() Method w3schools.com/jsref/jsref_concat_array.asp Commented Oct 6, 2015 at 11:38
  • 1
    @WinterMute Thanks, this is just what I was looking for. Commented Oct 6, 2015 at 11:40

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

hey thanks, @WinterMute suggested it in the comments. Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.