es6 删除数组中指定对象并返回新数组

2020-02-12  本文已影响0人  yuyuuuumi

If you know the index of an item

Suppose you have an array, and you want to remove an item in position i.

One method is to use slice():

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 2
const filteredItems = items.slice(0, i).concat(items.slice(i + 1, items.length))
// ["a", "b", "d", "e", "f"]

If you know the value

In this case, one good option is to use filter(), which offers a more declarativeapproach:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
// ["a", "b", "d", "e", "f"]

Removing multiple items

By index

You can just create a function and remove items in series:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
 
const removeItem = (items, i) =>
  items.slice(0, i-1).concat(items.slice(i, items.length))
 
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]

By value

You can search for inclusion inside the callback function:

const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]

Avoid mutating the original array

splice() (not to be confused with slice()) mutates the original array, and should be avoided.

上一篇 下一篇

猜你喜欢

热点阅读