0

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.

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I update my question both of them are string
Just data.filter(({ id }) => !ids.includes(id))
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.