0

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?

2 Answers 2

1

You have nested arrays, so use nested maps:

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);
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Problem solved. I knew there had to be an elegant solution, but have very little experience with JavaScript.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.