GURURAJ DHARANI GURURAJ DHARANI - 17 days ago 4
AngularJS Question

Array Mapping in AngularJs

I have two arrays

$scope.tags = [{ "id": 1, "name": "python" }, { "id": 2, "name": "NodeJs" }, { "id": 3, "name": "git" }]


Other one is

$scope.skillsInterested = [1,2];


What is want to do ?

How can i map the above arrays and print only names of the id's in
$scope.skillsInterested


I want to print names in first array only the id's present in second.

I have tried this after getting several answers

var tag_map = {};
for (var x = 0; x < $scope.tags.length; x++) {
tag_map[$scope.tags[x]['id']] = $scope.tags[x]['name'];
}
$scope.skillsInts = $scope.skillsInterested.map(function(x) {
return tag_map[x]


On running console.log

console.log("Result", tag_map);


It sometimes give result sometimes it gives 'map' of undefined.

TypeError: Cannot read property 'map' of undefined
at controllers.js:141
at angular.js:16383
at m.$eval (angular.js:17682)
at m.$digest (angular.js:17495)
at m.$apply (angular.js:17790)
at l (angular.js:11831)
at J (angular.js:12033)
at XMLHttpRequest.t.onload (angular.js:11966)


Thanks in advance.

Answer

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

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.