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.

1
  • 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). Commented Nov 2, 2015 at 15:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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 no, .filter() returns a filtered array (a new array). And note also that .indexOf() is internally looping over the "condition" array.
Makes sense! This is exactly what I needed it!

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.