I'm new to JavaScript Maps and I want to know if there's a way to delete an entry which key is an array, this is the way I'm trying to do it but it's not working:
/*
coffee map:
Map(8) {
'Roast' => 'Dark',
'Origin' => 'Chiapas',
304029198 => 'Batch serial number',
'Packed Date' => 20220134,
1045 => 'River One Store',
[ 10, 10, 9 ] => 'Quality Control',
true => 'Packed',
false => 'Not packed'
}
*/
coffee.delete([10, 10, 9]);
Thanks!
CodePudding user response:
Thanks to Rocky's comment I understood that it must be the same referenced Array to make a match
const arr2 = [1, 2, 3];
const myMap = new Map();
myMap.set(arr2, 'Nums');
console.log(myMap); // Map(1) { [ 1, 2, 3 ] => 'Nums' }
myMap.delete(arr2);
console.log(myMap); // Map(0) {}
CodePudding user response:
In JavaScript, there are primitive data types such as (string - number ...) and non-primitive data types (such as arrays). In non-primitive you access it by reference, so when you put an array as a key inside a map and then call that array inside the map.delete() you actually calling a different array with another reference. So you can declare the array outside the map and set it in the map using the variable name so you still use the same array reference as I did in the below code.
let coffee = new Map(); // Map Created
let arrayKey = [ 10, 10, 9 ];
coffee.set(arrayKey,"Quality Control"); // Set Key and Value to Map
// console.log(coffee); // To Check The Map Before Deleting
console.log(coffee.delete(arrayKey)); // True;
// console.log(coffee); // To Check The Map After Deleting
Or in my opinion, if you will put more than one array inside the map so put it as the value not as the key so you can easily access it as I did in the code below.
let coffee = new Map();
coffee.set('Quality Control',[ 10, 10, 9 ]); // Set Key and Value to Map
// console.log(coffee); // To Check The Map Before Deleting
console.log(coffee.delete("Quality Control")); // True;
// console.log(coffee); // To Check The Map After Deleting