美文网首页
es6 删除数组中指定对象并返回新数组

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

作者: yuyuuuumi | 来源:发表于2020-02-12 15:12 被阅读0次

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.

相关文章

  • js 数组操作合集(主要针对对象数组)

    1,根据对象中元素 查找对象数组中对应的元素 2,删除数组中指定对象的元素 并返回删除后的数组 3,js数组实现权...

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

    If you know the index of an item Suppose you have an arra...

  • es6从数组中删除指定元素

    ES6从数组中删除指定元素 --by Affandi ⊙▽⊙

  • js数组自己封装小方法

    提取数组中指定参数,并返回该参数的集合应用场景:在一个数组对象中想要直接获取某个参数值的集合 传入指定对象数组,就...

  • lodash与30-seconds-code中的数组对象

    1. maxBy: 数组对象中返回指定属性中最大的值 lodash ES6 2.differenceBy: 找不同...

  • 数组删除指定元素

    数组删除指定元素,返回被删除的元素

  • js操作数组的方法

    push()数组最后添加并返回长度unshift()数组前面添加并返回长度pop()数组最后删除并返回值shift...

  • 数组对象方法

    数组的删除 数组的删除分为删除并返回第一个元素shift(),或者删除并返回最后一个元素pop() 数组的添加 数...

  • 数组操作

    unshift:将参数添加到原数组开头,并返回数组的长度 pop:删除原数组最后一项,并返回删除元素的值;如果数组...

  • 数组

    1、数组倒序输出 2、删除数组中指定下标对象 3、根据条件获取数组中指定对象下标 4、遍历数组 4、过滤数组

网友评论

      本文标题:es6 删除数组中指定对象并返回新数组

      本文链接:https://www.haomeiwen.com/subject/cqhcfhtx.html