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

array.remove(value);

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


当前回答

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

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]

其他回答

const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]

假设你想从Arr删除3号

const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]

使用过滤器是实现此要求的优雅方式。 过滤器不会改变原始数组 。

const num = 3; 允许 rr = [1, 2, 3, 4]; const arr2 = arr. filter(x xx x x !x != num); 控制台. log (rr); / / [1, 2, 3, 4] 控制台. log(rr2) / / [1, 2, 4]

如果您想要实现突变删除行为, 您可以使用过滤器, 然后将结果指定到原始数组 。

constnum = 3; let arr = [1, 2, 3, 4]; arr = arr. filter(x x \ x = = = = = = = = = = = = = = = = = =; 控制台. log(rr); / / [1, 2, 4]

顺便说一下, 过滤器将删除在条件中匹配的所有事件( 不仅仅是第一次发生) , 就像您在下面的例子中看到的一样 。

const num = 3; 允许 rr = [1, 2, 3, 3, 3, 3, 4]; arr = arr. filter(x x x x x = = = = = = = = num; 控制台. log (rr); / / [1, 2, 4]

万一您只想删除第一种情况,您可以使用复数法

onst num = 3; 让 arr = [1, 2, 3, 3, 3, 3, 4]; const idx = rr. indexof( num); arr.spice( idx, idx) = = 1 = 1 = 1 = 1 ; 控制台. log( rr) = [ 1, 2, 3, 3, 3, 4] / [ 1, 3, 3, 4]

最简单的方法可能是使用过滤功能。例如:

让数组 = ["哈罗","世界"] 让新数组 = 数组. filter (项目 \\\ 项 ! =@ hello ) ; 控制台. log (新数组) ; // ["世界" ]

如果您使用现代浏览器, 您可以使用. 过滤器 。

Array. prototype. remove = 函数 (x) { 返回此. filter( 函数 (v) { 返回 v $ ylexx; } ; } ; var a = ["a", b", c"]; var b = a. remove ('a' );

使用.indexof () 和.spolice () - 可变模式

这里有两种情况:

我们知道指数

康斯特饮料 = [“Tea”、“咖啡 ”、“Milk ”]; 康斯特 id = 1; 康斯特 删除饮料 = 饮料.splice(id, 1); 控制台.log (removedDrink)

我们不知道指数,但知道它的价值。 Const drinks = [“Tea”,“Coffee”,“Milk”]; const id = drinks.indexof (“Coffee”);// 1 Const moved Drink = drink.spice(id,1);// / [“Coffee”] 控制台.log(removedDrink);// [“Tea”,“Milk” 控制台.log(drinks);

使用. filter () - 不可变模式

你可以想到的最好方式是 — — 而不是“删除”该项目,而是“创造”一个新的阵列,只是不包含该项目。 所以我们必须找到它,完全省略它。

康斯特饮料 = [“Tea”、“Coffee”、“Milk ”]; Const id = “Coffee”; Const idx = drinks.indexof(id); 康斯特 移除的Drink = 饮料 [idx]; 康斯特过滤的饮料 = 饮料 ; Const 过滤的Drinks = 饮料 . filter ((饮料,索引) 饮料 = 去除的Drink); 控制室.log (“ Filter 饮料阵列 :”+过滤的饮料 ); 控制室.log (“ 原件饮料阵列 :” +饮料 );