-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);

3

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

Comments

0
let newData = data.filter(item => !id.includes(item.id));
console.log(newData);

Comments

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);

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.