Shahariar Rahman Sajib
Shahariar Rahman Sajib

Reputation: 157

How to filter and get array by id?

const id = [1, 4, 10]
const data =[{id: 1, name: Banana}, {id: 2, name: Mango}, {id: 3, name: Chili}, {id: 4, name: WaterMelon},  {id: 10, name: WaterMelon}]

I tried filter It's showing me empty value. I want to remove matched by id in an array.

Upvotes: 2

Views: 145

Answers (4)

SJK
SJK

Reputation: 16

const result=data.filter((value)=>!id.includes(value.id))

Upvotes: 0

Miheo
Miheo

Reputation: 515

If you want to filter out matched ID, try this code:

const result = data.filter(({id}) => ids.indexOf(id) < 0);

const ids = [1, 4, 10]
const data =[{id: 1, name: 'Banana'}, {id: 2, name: 'Mango'}, {id: 3, name: 'Chili'}, {id: 4, name: 'WaterMelon'},  {id: 10, name: 'WaterMelon'}];

const result = data.filter(({id}) => ids.indexOf(id) < 0);
console.log(result);

Upvotes: 1

Vicky Krisna
Vicky Krisna

Reputation: 26

using filter it will select the ids of data, and your object name type data should be string or maybe you want it as a variable so you will not get error.

data.filter((object) => !id.includes(object.id))

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

Use filter() with includes():

const result = data.filter(({id}) => !ids.includes(id));

Full snippet:

const ids = [1, 4, 10];
const data = [{
  id: 1,
  name: 'Banana'
}, {
  id: 2,
  name: 'Mango'
}, {
  id: 3,
  name: 'Chili'
}, {
  id: 4,
  name: 'WaterMelon'
}, {
  id: 10,
  name: 'WaterMelon'
}];

const result = data.filter(({id}) => !ids.includes(id));

console.log(result);

Upvotes: 2

Related Questions