Code Junkie
Code Junkie

Reputation: 83

Replacing for loops with map method in JavaScript

I have this code that is working...

var allSummaries = [ {id: "1", name: "Example1"},  {id: "2", name: "Example2"}, {id: "3", name: "Example3"}, {id: "4", name: "Example4"},  {id: "5", name: "Example5"}, {id: "6", name: "Example6"}, {id: "7", name: "Example7"}, {id: "8", name: "Example8"}, {id: "9", name: "Example9"}, {id: "10", name: "Example10"}, ];

var uniqueSummaries = ["4","6","9"];

function extractSpecificSummaries(arr1, arr2) {
   var summariesBasedOnIDs = [];
   for (var i = 0; i <= arr1.length - 1; i++) {
      for (var x = 0; x <= arr2.length -1; x++) {
         if (arr1[i].id == arr2[x]) {
           summariesBasedOnIDs.push(arr1[i]);

         }

      }
   }
   return summariesBasedOnIDs;
}


var summaries = extractSpecificSummaries(allSummaries, uniqueSummaries);

But I want to make it look better by replacing the for loops with the map method. I know there is a simpler way to refactor this code. Does anyone have an idea how to do this?

Thanks!

Upvotes: 2

Views: 1152

Answers (2)

Scott Sauyet
Scott Sauyet

Reputation: 50787

I would make a fairly generic extract function for this:

const extract = (objs, keys) => objs.filter(obj => keys.some(key => obj.id === key))
extract(allSummaries, uniqueSummaries) //=> [{id: '4', name: 'Example4'}, {id: '6',... ]

The only reasonable way I can see to further generalize this would be if we allowed a function on obj and key rather than simply testing id.

Upvotes: 0

dhilt
dhilt

Reputation: 20744

I would use a combination of filter and some Array.prototype methods:

const result = allSummaries.filter(i => uniqueSummaries.some(u => u === i.id));

console.log(result); // [{id: "4", name: "Example4"}, {id: "6", name: "Example6"}, {id: "9", name: "Example9"}]

Upvotes: 3

Related Questions