-3

I want to remove all the object from a data array that contains the same id in an array of id. How can I achieve this task without looping it?

const id = [1, 2];
const data = [
    {id: 1},
    {id: 2},
    {id: 3}
];
console.log(data);
Jerry D
  • 381
  • 11
  • 25
Rushabh Shah
  • 133
  • 1
  • 4
  • 2
    This has been asked so many times in SO that I'll make it only as a comment: `const filtered = data.filter((item) => id.includes(item.id))` – Samuli Hakoniemi Mar 07 '19 at 13:12
  • 1
    Possible duplicate of [filtering an array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filtering-an-array-of-objects-based-on-another-array-in-javascript) and [Filter Array Not in Another Array](https://stackoverflow.com/questions/33577868) – adiga Mar 07 '19 at 13:17
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Mar 07 '19 at 13:18

4 Answers4

1

You can try with Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

and Array.prototype.includes():

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const id = [1, 2];
const data = [
    {id: 1},
    {id: 2},
    {id: 3}
];
var res = data.filter(i => !id.includes(i.id)); 
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0
let newData = data.filter(item => !id.includes(item.id));
console.log(newData);
0

You can use .filter() and .includes() for filtering your object.

const id = [1, 2];
let data = [
    {id: 1},
    {id: 2},
    {id: 3}
];

data = data.filter((item) => (!id.includes(item.id)));

console.log(data);
Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33
0

You can use method uniqBy from lodash https://lodash.com/docs/4.17.11#uniqBy

const uniqArray = _.uniqBy([{ 'id': 1 }, { 'id': 2 }, { 'id': 1 }], 'id');

console.log(uniqArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Igor Litvinovich
  • 2,436
  • 15
  • 23