最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to remove objects from an array which match another array of ids - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 4

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)
发布评论

评论列表(0)

  1. 暂无评论