Home > Net >  keeping elements in array when adding new elements
keeping elements in array when adding new elements

Time:10-30

Can't keep data in the array when adding new. This code is in a loop btw

let placeHolder = facArray[key].filter(i => i.M == map).map(i => i.W)
    mapArray[map] = [...placeHolder]

I am trying to store data in an array with the value of map as an index and I would like to push data to it this is in a loop btw but it keeps removing the previous data how do I keep the previous data while adding to it

CodePudding user response:

You need to put a reference to the non-primitive instance of Array, to use as a Map key. For reference :

    var mapArray = new Map();
    ...
    ...
    let placeHolder = facArray[key].filter(i => i.M == map).map(i => i.W)
    mapArray.set(map,[...placeHolder]);
    ...
    ...

CodePudding user response:

I needed to make sure there was actually something in the array before i could use the spread operater to get all the old data

if(mapArray[map] === undefined){
    mapArray[map] = [...placeHolder]
}else{
    mapArray[map] = [...placeHolder, ...mapArray[map]]
}

CodePudding user response:

You can also do it with a simple Array.push():

const mapArray={abc:[1,3,5,7]}, map="abc", 
  placeHolder=[2,4,6,8];

(mapArray[map]??=[]).push(...placeHolder);

console.log(mapArray[map]);

The expression (mapArray[map]??=[]) will initialise an Array in mapArray in case it did not exist before.

  • Related