1

I have been trying to figure out the cleanest way to filter an array of objects without using nested loops. I found this post using .filter function about filtering an array using another array but I failed on figuring out how to actually access the right key within the object in array of objects using the same pattern Given the next following array of objects:

[ { technology: 'CHARACTER', score: -1 },
{ technology: 'PRESSURE_RELIEF', score: 2 },
{ technology: 'SUPPORT', score: 3 },
{ technology: 'MOTION_ISOLATION', score: 2 },
{ technology: 'TEMPERATURE_MANAGEMENT', score: -1 },
{ technology: 'COMFORT', score: 2 } ]

I want to use the following array to filter the ones I don't need:

[CHARACTER, MOTION_ISOLATION, TEMPERATURE_MANAGEMENT]

Is it even possible to access it without using a nested loop? I'm also open to suggestions if not possible.

Community
  • 1
  • 1
mauricioSanchez
  • 366
  • 10
  • 23
  • You can do it without nested loops by using something other than an array to hold the keys to search for. If you use an array, then *something* is going to have to iterate through the array in order to find a match (or determine there's no match). – Pointy Nov 02 '15 at 15:10

1 Answers1

6

You can use .filter with .indexOf like so

var condition = ['CHARACTER', 'MOTION_ISOLATION', 'TEMPERATURE_MANAGEMENT'];

var data = [ 
  { technology: 'CHARACTER', score: -1 },
  { technology: 'PRESSURE_RELIEF', score: 2 },
  { technology: 'SUPPORT', score: 3 },
  { technology: 'MOTION_ISOLATION', score: 2 },
  { technology: 'TEMPERATURE_MANAGEMENT', score: -1 },
  { technology: 'COMFORT', score: 2 } 
];

var result = data.filter(function (el) {
  return condition.indexOf(el.technology) < 0;
});

console.log(result);
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
  • This looks awesome! Thanks so much. Will .filter return me a new object without the elements I'm filtering? And pls correct me if I'm wrong but I thought .filter when passing a callback will return a boolean. – mauricioSanchez Nov 02 '15 at 15:12
  • 1
    @mauricioSanchez no, `.filter()` returns a filtered array (a **new** array). And note also that `.indexOf()` is internally looping over the "condition" array. – Pointy Nov 02 '15 at 15:14
  • Makes sense! This is exactly what I needed it! – mauricioSanchez Nov 02 '15 at 15:15