Home > Back-end >  how to use filter on array of objects in javascript
how to use filter on array of objects in javascript

Time:04-17

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.

CodePudding user response:

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

CodePudding user response:

If the type of id in the original array differs from the type of id in the data, you can use .map(a=>parseInt(a)) and then check with .includes()

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 ids_int  = ids.map(a => parseInt(a))
const filtered = data.filter(x => !ids_int.includes(x.id))
console.log(filtered)

  • Related