Skip to content Skip to sidebar Skip to footer

How To Filter Object Array Using An Array In Js?

I hope you're having a great day. This is pretty straight-forward. I have an object array which I want to filter out, with the help of another array. Scenario is illustrated below:

Solution 1:

You could use Array.includes instead of iterating over my_array:

var ob_array = [{
    'a': 1,
    'col_2': 'abc'
  },
  {
    'a': 2,
    'col_2': 'xyz'
  },
  {
    'a': 3,
    'col_2': 'jkl'
  }
];

var my_array = [1, 2];

console.log(ob_array.filter(ob => !my_array.includes(ob.a)))

Solution 2:

The Array#filter takes a predicate i.e. a callback that returns true or false. if true is returned the element is allowed and false otherwise.

You are not returning the boolean result from your predicate callback, your code can be modified as below to return false if the element with key a exists in my_array or true otherwise:

var ob_array = [{
    'a': 1,
    'col_2': 'abc'
  },
  {
    'a': 2,
    'col_2': 'xyz'
  },
  {
    'a': 3,
    'col_2': 'jkl'
  }
];

var my_array = [1, 2];

const res = ob_array.filter(function(i) {
  for (var j of my_array) {
    if (i['a'] === j) {
      returnfalse;
    }
  }
  returntrue;
});

console.log(res);

But a more elegant approach exists with the help of Array#includes:

var ob_array = [{
    'a': 1,
    'col_2': 'abc'
  },
  {
    'a': 2,
    'col_2': 'xyz'
  },
  {
    'a': 3,
    'col_2': 'jkl'
  }
];

var my_array = [1, 2];

console.log(ob_array.filter(o => !my_array.includes(o.a)));

Solution 3:

Use filter and includes

var ob_array = [
                  {'a' : 1, 'col_2' : 'abc'},
                  {'a' : 2, 'col_2' : 'xyz'},
                  {'a' : 3, 'col_2' : 'jkl'}
                 ];

var my_array = [1, 2];

const res = ob_array.filter(({a}) => !my_array.includes(a));

console.log(res)

Solution 4:

[{'a' : 1, 'col_2' : 'abc'},
              {'a' : 2, 'col_2' : 'xyz'},
              {'a' : 3, 'col_2' : 'jkl'}
             ].filter(function(i){return (i.a!=1 && i.a!=2)})

the above code gives the required output.

Post a Comment for "How To Filter Object Array Using An Array In Js?"