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

array.remove(value);

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


当前回答

我测试过splicefilter查看哪个速度更快 :

let someArr = [...Array(99999).keys()] 

console.time('filter')
someArr.filter(x => x !== 6666)
console.timeEnd('filter')

console.time('splice by indexOf')
someArr.splice(someArr.indexOf(6666), 1)
console.timeEnd('splice by indexOf')

在我的机器上splice更快。这有道理,因为splice仅编辑现有的数组,而filter创建新数组。

尽管如此,filter逻辑上更清洁(容易阅读),更适合使用不可改变状态的编码风格。所以由你决定是否进行这种权衡决定。

其他回答

您可以使用lodash_.pull(平衡数组). pullAt(阵数数组)或_. 无 _(不变异阵列)

var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']

var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']

var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']

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

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]

答案已经很多了, 但是因为还没有人用一个衬里来做, 我想我会展示我的方法。 它会利用字符串. split () 函数在创建数组时将删除所有指定字符这一事实。 这里举一个例子 :

var ary = [1,2,3,4,1234,10,4,5,7,3];
out = ary.join("-").split("-4-").join("-").split("-");
console.log(out);

在此示例中, 所有 4 个的字符都在从数组中移除 。 但是, 必须指出, 包含字符“ - ” 的任何数组都会与此示例产生问题 。 简而言之, 这会导致组合( “ - ” ) 函数不适当地将您的字符串拼凑在一起。 在这种情况下, 上面的扇形中的所有“ - ” 字符串都可以替换为在原始数组中不会使用的任何字符串 。 以下还有一个示例 :

var ary = [1,2,3,4,'-',1234,10,'-',4,5,7,3];
out = ary.join("!@#").split("!@#4!@#").join("!@#").split("!@#");
console.log(out);

我知道答案已经很多了,但其中许多答案似乎都使问题复杂化了。这是一个简单的、循环性的方法,可以删除所有键的所有例子——在找不到索引之前自调键,直到找不到索引。是的,它只在浏览器中起作用。indexOf,但它很简单,并且很容易被多填填充。

独立职能

function removeAll(array, key){
    var index = array.indexOf(key);

    if(index === -1) return;

    array.splice(index, 1);
    removeAll(array,key);
}

原型方法

Array.prototype.removeAll = function(key){
    var index = this.indexOf(key);

    if(index === -1) return;

    this.splice(index, 1);
    this.removeAll(key);
}

使用 jQuery 的阵列 :

A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`   

注意: 如果元素未找到, 在阵列中返回 - 1 。