I got an array of id's. I also have another array of objects. I would like to remove those objects which match with the array of id's. Below is the pseudo code for the same. Can someone help me with the best approch?
const ids = ['1', '2'];
const objs = [
{
id: "1",
name : "one",
},
{
id: "1",
name : "two"
},
{
id: "3",
name : "three",
},
{
id: "4",
name : "four"
},
];
ids.forEach(id => {
const x = objs.filter(obj => obj.id !== id )
console.log('x ==', x);
});
I got an array of id's. I also have another array of objects. I would like to remove those objects which match with the array of id's. Below is the pseudo code for the same. Can someone help me with the best approch?
const ids = ['1', '2'];
const objs = [
{
id: "1",
name : "one",
},
{
id: "1",
name : "two"
},
{
id: "3",
name : "three",
},
{
id: "4",
name : "four"
},
];
ids.forEach(id => {
const x = objs.filter(obj => obj.id !== id )
console.log('x ==', x);
});
Share
Improve this question
edited Jan 24, 2021 at 17:07
terrymorse
7,0961 gold badge23 silver badges31 bronze badges
asked Jan 24, 2021 at 16:34
ManoharManohar
1,1852 gold badges11 silver badges16 bronze badges
4 Answers
Reset to default 4Use filter
and includes
method
const ids = ["1", "2"];
const objs = [
{
id: "1",
name: "one",
},
{
id: "1",
name: "two",
},
{
id: "3",
name: "three",
},
{
id: "4",
name: "four",
},
];
const res = objs.filter(({ id }) => !ids.includes(id));
console.log(res);
You can put the ids
in a Set
and use .filter
to iterate over the array of objects and .has
to check if the id
is in this set
:
const ids = ['1', '2'];
const objs = [
{ id: "1", name : "one" },
{ id: "1", name : "two" },
{ id: "3", name : "three" },
{ id: "4", name : "four" },
];
const set = new Set(ids);
const arr = objs.filter(obj => !set.has(obj.id));
console.log(arr);
1st requirement -> you have to check for all elements in id array way to do that using array's built in method is array.includes() or indexof methods
2nd Requirement -> pick out elements not matching with ur 1st requirement which means filter the array.
Combile two
arr = arr.filter(x => !ids.includes(x.id))
Cool es6 destructung syntax
arr = arr.filter(({id}) => !ids.includes(id))
const ids = ['1', '2'];
const objs = [
{
id: "1",
name : "one",
},
{
id: "1",
name : "two"
},
{
id: "3",
name : "three",
},
{
id: "4",
name : "four"
},
];
let arr = objs.filter(function(i){
return ids.indexOf(i.id) === -1;
});
console.log(arr)