0

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

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 4
    Your question consists of one run-on sentence which is confusing. Can you try to clarify your question? – Michael M. Oct 29 '22 at 02:35
  • I do not understand what you are trying to do or, more importantly, why you are using this intermediary placeholder array. You say "push" data, do you know about https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push ? – msanford Oct 29 '22 at 02:36
  • try using `Array.concat()` method instead of `mapArray[map] = [...placeHolder]` https://stackoverflow.com/questions/4156101/copy-array-items-into-another-array – Spencer May Oct 29 '22 at 03:17

3 Answers3

0

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]);
    ...
    ...
bigstack
  • 1
  • 2
0

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]]
}
0

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.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43