Skip to content
Advertisement

how to use filter on array of objects in javascript

I want to filter my result in javascript.

const ids =["2", "3"];
const data = 
  [
    {"id":'1', 'name:'alex' , 'subject':'english' },
    {"id":'2', 'name:'alex' , 'subject':'english' },
    {"id":'3', 'name:'alex' , 'subject':'english' },
    {"id":'4', 'name:'alex' , 'subject':'english' },
  ]

I want to filter data and remove those id’s found in ids. This is what I have tried so far

const NewData = ids.reduce(function (key, index) {
  return (data.filter(x => x.id !== key))
})

But it returns

[
  {"id":'1', 'name:'alex' , 'subject':'english' },
  {"id":'3', 'name:'alex' , 'subject':'english' },
  {"id":'4', 'name:'alex' , 'subject':'english' },
]

I want to remove id 2 & ‘3’ from data but it only remove id 2.Hope You understand my issue.

Advertisement

Answer

No need to use reduce. A simple filter will work.

Example:

const ids = ["2", "3"];

const data = [
  { id: "1", name: "alex", subject: "english" },
  { id: "2", name: "alex", subject: "english" },
  { id: "3", name: "alex", subject: "english" },
  { id: "4", name: "alex", subject: "english" },
];

const new_data = data.filter((x) => ids.includes(x.id));
console.log(new_data);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement