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

本文标签: javascriptHow to remove objects from an array which match another array of idsStack Overflow