fzlrhmn fzlrhmn - 3 months ago 18
Javascript Question

Remove object by array in javascript

I want to remove object from array that matches the

id
from array, like this one

var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title: "title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];


I just want to remove an object that matches in an array. The result that I expected is like

var report = [{ id:4, title: "title 4"},{ id:5, title: "title 5"}];


I have used
.splice.
method on
.forEach
but it seems doesn't work so well.

Any help will be appreciated :)

Answer

You can use filter() and indexOf()

var report = [{ id:1, title: "title 1"},{ id:2, title: "title 2"},{ id:3, title: "title 3"},{ id:4, title: "title 4"},{ id:5, title: "title 5"}];
var array = [1,2,3];

var result = report.filter(function(e) {
  return array.indexOf(e.id) == -1;
})

console.log(result)