Home > Back-end >  Most efficient way to remove objects from array based on key value objects in another array
Most efficient way to remove objects from array based on key value objects in another array

Time:05-26

Given the excludes and items arrays, I want to return an array of objects from items that don't contain a key, value pair corresponding to a key, value pair object in excludes. Is there a better way of solving this other than using nested for loops?

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}];

const items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}];

//Expected output: [{color: "Blue", score: 100, age: 20}]

CodePudding user response:

Use filter() to filter the items array. The filtering criteria checks each of the properties of the item against the excludes array. If none of them match, the item is included in the result.

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}];

const items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}];

let result = items.filter(item =>
  !Object.entries(item).some(([key, value]) => 
    excludes.find(e => e.key = key && e.value == value)));
console.log(result);

CodePudding user response:

You can use Array#filter, as suggested by @Barmar, in combination with Array#every as follows:

const excludes = [{key: "color", value: "Red"}, {key: "age", value:12}, {key:"score", value: 75}],
      items = [{color: "Red", score: 30, age: 12}, {color: "Blue", score: 100, age: 20}, {color: "Red", score: 75, age: 30}],
      
      output = items.filter(
          item => excludes.every(
              ({key,value}) => item[key] !== value
          )
      );

console.log( output );
//OUTPUT: [{color: "Blue", score: 100, age: 20}]

  • Related