如何从数组中删除一个特定值? 类似 :

array.remove(value);

制约:我必须使用核心 JavaScript 。 框架不允许 。


当前回答

删除单个元素

function removeSingle(array, element) {
    const index = array.indexOf(element)
    if (index >= 0) {
        array.splice(index, 1)
    }
}

删除多个元素, 位置内

这对于确保算法在O(N)时间运行更为复杂。

function removeAll(array, element) {
    let newLength = 0
    for (const elem of array) {
        if (elem !== number) {
            array[newLength++] = elem
        }
    }
    array.length = newLength
}

删除多个元素,创建新对象

array.filter(elem => elem !== number)

其他回答

我测试了复数和过滤器 看哪个更快:

let someArr = [... Array(999999). keys ()] 控制台.time(“ filter” ) someArr. filter(x x = = = = = 666666) 控制台.timeEnd(“ filter ” ) 控制台.time(“ splice by indexof ” ) someArr. splice( some Arr. indexof( 6666), 1) 控制台.timeEnd( “ splice by indexof ” )

在我的机器上, 复数会更快。 这有道理, 因为复数只编辑一个已有的数组, 而过滤器会创建一个新的数组 。

因此,过滤器在逻辑上是更清洁的(更容易阅读),并且更适合使用不可改变状态的编码风格。因此,由你来决定你是否想做出这种权衡。

除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...

const removeItem = 
    idx => 
    arr => 
    arr.reduce((acc, a, i) =>  idx === i ? acc : acc.concat(a), [])

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

...或者一个循环函数(诚实地说不是那么优雅...也许有人有更好的循环解决方案? ? )...

const removeItemPrep = 
    acc => 
    i => 
    idx => 
    arr => 

    // If the index equals i, just feed in the unchanged accumulator(acc) else...
    i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :

    // If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else... 
    acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) : 

    // return the accumulator
    acc 

const removeItem = removeItemPrep([])(0)

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

您可以使用 Set 代替并使用删除函数 :

const s = Set;
s.add('hello');
s.add('goodbye');
s.delete('hello');

通过传递其值来删除项目 --

const remove=(value)=>{
    myArray = myArray.filter(element=>element !=value);

}

将项目通过索引编号删除 -

  const removeFrom=(index)=>{
    myArray = myArray.filter((_, i)=>{
        return i!==index
    })
}

虽然大多数先前的答复都回答了这个问题,但是为什么没有使用切片()方法还不够清楚。 是的,过滤器()符合不可改变的标准,但做以下更短的等值如何?

const myArray = [1,2,3,4];

现在让我们说我们应该从阵列中删除第二个元素, 我们可以简单地做到:

const newArray = myArray.slice(0, 1).concat(myArray.slice(2, 4));

// [1,3,4]

今天,社区强烈鼓励从阵列中删除元素,因为其简单和不可改变的性质。 一般来说, 导致突变的方法应该避免。 例如, 鼓励您将推( ) 替换为 concat () , 并用切片 () 替换为 plus () 。