admin管理员组文章数量:1399119
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)
本文标签: javascriptHow to remove objects from an array which match another array of idsStack Overflow
版权声明:本文标题:javascript - How to remove objects from an array which match another array of ids - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744137114a2592448.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论