0

I have the following code which is inside for each loop

    let array:[];

    result =  campaignsPerAffiliate.map(campaign => campaign.id)// returns 0001,00ec6,0caa4

now I want to push all these to an array one after another and because we are inside for each there will be more numbers so I will end up with [0001,00ec6,0caa4,000,1111]

  result.forEach(element => {
  array=array.push(element)
});

this doesnt seem to work

3
  • 2
    Remove array=. It's setting the whole array to the result of array.push, which will only be one value. Consider creating a copy instead? array = result.slice() Commented Oct 20, 2020 at 11:54
  • 1
    Is array defined variable? Share all of the foreach loop which you are talking about. Commented Oct 20, 2020 at 11:56
  • 1
    I know you didn‘t ask but array=array.concat(result) would also work. Commented Oct 20, 2020 at 11:58

1 Answer 1

1

Array.push returns the new length of the array, not the array. Thus, if you want to do it your way, you need to remove array=.

However, combining arrays can be done much easier with Array.concat.

See an example of both working properly here:

let array = [];
let result = ["001", "002", "003"];
console.log("With concat: ", array.concat(result));
result.forEach(val=>{
  array.push(val);
});
console.log("With forach: ", array);

Sign up to request clarification or add additional context in comments.

Comments

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.