deals4us3
deals4us3

Reputation: 35

how to push map to a new array using javascript

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

Upvotes: 0

Views: 1450

Answers (1)

Nate Levin
Nate Levin

Reputation: 1118

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

Upvotes: 1

Related Questions