Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter an Array with another Array

I have an Array of Objects:

const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }]

I have a second array containing the ID's that I want to filter out of the first Array:

const ids = [1, 2]

How do I create a new Array of Objects without the ID's found in ids.

like image 562
Antek Avatar asked Aug 29 '26 19:08

Antek


2 Answers

This is a fairly simple filter operation

const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }];

const ids = [1, 2];

var result = array.filter( x => !ids.includes(x.id));
console.log(result);
like image 156
Jamiec Avatar answered Sep 01 '26 07:09

Jamiec


If you need to mutate the original array you can do like this:

const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }];

const ids = [1, 2];

ids.forEach(idToDelete => {
    const index = array.findIndex(({ id }) => id === idToDelete);
    array.splice(index, 1);
});

console.log(array);

If you need a new array you can do like this:

const array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }];

const ids = [1, 2];

const result = array.filter(({ id }) => !ids.includes(id));

console.log(result);

You could also reassign a new array to the array variable:

let array = [{id: 1, bar: "test" }, {id: 2, bar: "test2" }, {id: 3, bar: "test3" }];

const ids = [1, 2];

array = array.filter(({ id }) => !ids.includes(id));

console.log(array);
like image 24
Guerric P Avatar answered Sep 01 '26 08:09

Guerric P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!