Reputation: 3
Is there any way to use Map.get() with an array of arrays (specifically in d3.js)?
Here's what I have: (1) Map – containing data in over 100 key-value pairs (2) Array of arrays – listing the keys of the data I want to pull from the Map for populating a table (only a subset of the 100+ values)
Here's what I need to create: (1) A new array of arrays – this new array should take each item from the first array in turn, look up the key in the Map and return the value.
I can get Map.get() to work just fine over a single array, but only if I specify the index of the nested array, like this:
var myMap;
var dataArray = [key_1, key_2, key_3, key_4, key_5, key_6]
var newArray = dataArray[0].map(function(d) {
return myMap.get(d);
});
But when my original array is an array of arrays, I can't figure out how to do it:
var myMap;
var dataArray = [
[key_1, key_2, key_3],
[key_4, key_5, key_6],
[key_7, key_8, key_9]
]
var newArray = ???
Any suggestions?
Upvotes: 0
Views: 113
Reputation: 26181
Not only or 2D but for an indefinite ND array of keys you may also do as follows;
var myMap = new Map(),
dataArray = [["key_1", "key_2", ["key_31", "key_32", ["key_331"]]],
["key_4", "key_5", ["key_61", "key_62", ["key_631"]]],
["key_7", "key_8", ["key_91", "key_92", ["key_931"]]]
],
getMap = (a,m) => a.map(k => Array.isArray(k) ? getMap(k,m) : m.get(k));
console.log(JSON.stringify(getMap(dataArray,myMap)));
Upvotes: 0
Reputation: 1074684
You have nested arrays, so use nested map
s:
var newArray = dataArray.map(function(array) {
return array.map(function(d) {
return myMap.get(d);
});
});
If creating functions in loops bothers you, you can split the recreated function out:
var newArray = dataArray.map(function(array) {
return array.map(mapOne);
});
function mapOne(array) {
return array.map(function(d) {
return myMap.get(d);
});
}
Upvotes: 1