Array Mapping in AngularJs

Make a map of your data that looks like this:

var tagMap = { 1: "python", 2: "NodeJs" /* etc. */ };

You can do this by looping over your tags and adding a new property to an object. reduce lets you do this without creating any extra variables.

Then, you can select names from your newly created object using the [] notation: tagMap[1] returns "pyhton".

var tags =  [{ "id": 1, "name": "python" }, { "id": 2, "name": "NodeJs" }, { "id": 3, "name": "git" }]
var selectedExpTags = [1,2];


// Make a map for `id: name`
var tagMap = tags.reduce(function(map, tag) {
  map[tag.id] = tag.name;
  return map;
}, {});

// Quickly select names from the map:
var selectedNames = selectedExpTags.map(function(id) {
  return tagMap[id];
});

console.log(selectedNames);

Expand snippet

Using this approach, you minimise the iterations over your data. The creation of the map loops over the tags once. Creating the array with names, loops over the selected tags once. So, roughly, the “loop count” is tags.length + selectedTags.length. If you would use an indexOf based approach, your loop count would be tags.length * selectedTags.length.

Leave a Comment