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); });
Use 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.