Reputation: 366
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.
Upvotes: 1
Views: 2755
Reputation: 77482
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);
Upvotes: 6