0

I can't seem to find a solution to this, how do you remove items from an array based on an array of values? The same way you remove one?


const [items, setItems] = useState([
  {id: 1, name: "foo"},
  {id: 2, name: "bar"},
  {id: 3, name: "baz"}
])

I need to remove some ids:

const idsToRemove = [1,3]

// I thought I'd loop
idsToRemove.map(i => items.filter(item => item.id !== i))

This will return an array and something does not feel right at all. If it was to remove one item then that would be ok but removing items from array by an array of ids I not know where to start.

In the loop, I tried to use delete but "undefinded" is in the array: [undefined]:

idsToRemove.map(i => items.map(item => delete item.id === i))

So far React says you cannot update state during a loop. Based on idsToRemove, how can I end up with one item in the state?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Sylar
  • 11,422
  • 25
  • 93
  • 166

4 Answers4

2

You need to put the filter call outside:

items.filter(item => !idsToRemove.includes(item.id))
trincot
  • 317,000
  • 35
  • 244
  • 286
1

You can use filter with includes.

items = items.filter(({id})=>!idsToRemove.includes(id));

let items = [
  {id: 1, name: "foo"},
  {id: 2, name: "bar"},
  {id: 3, name: "baz"}
];
const idsToRemove = [1,3]
items = items.filter(({id})=>!idsToRemove.includes(id));
console.log(items);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

const items = [
  {id: 1, name: "foo"},
  {id: 2, name: "bar"},
  {id: 3, name: "baz"}
];

const idsToRemove = [1, 3];

console.log(
  items.filter(({ id }) => !idsToRemove.includes(id))
);
gkucmierz
  • 1,055
  • 1
  • 9
  • 26
1

const [items, setItems] = useState([
  {id: 1, name: "foo"},
  {id: 2, name: "bar"},
  {id: 3, name: "baz"}
]
const idsToRemove = [1,3]

setItems(items.filter((item)=> !idsToRemove.includes(item.id)))

using functional programming you won't be changing the current state obj but creating a new one, hence maintaining the sanity of React immutability.

Sheelpriy
  • 1,675
  • 17
  • 28