如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
当前回答
我本人也有这个问题(在更换阵列是可以接受的情况下),
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
要给上面的片段略加上下文:
self.thingWithItems = {
items: [],
removeItem: function (item) {
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
this.items = filteredItems;
}
};
此解决方案应该同时使用引用项和值项。 它都取决于您是否需要保持对原始数组的引用, 以判断该解决方案是否适用 。
其他回答
通过传递其值来删除项目 --
const remove=(value)=>{
myArray = myArray.filter(element=>element !=value);
}
将项目通过索引编号删除 -
const removeFrom=(index)=>{
myArray = myArray.filter((_, i)=>{
return i!==index
})
}
使用过滤过滤器这是达到这一要求的优雅方式。filter
将不改变原始数组。
const num = 3;
let arr = [1, 2, 3, 4];
const arr2 = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 4]
您可以使用filter
然后将结果指定为原始数组,如果你想实现突变清除行为的话。
const num = 3;
let arr = [1, 2, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
顺便说一句,filter
将删除在条件中匹配的所有事件( 不只是第一次发生) , 正如您在下面的示例中看到的一样
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
万一您只想删除第一种情况,您可以使用复盘方法
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
const idx = arr.indexOf(num);
arr.splice(idx, idx !== -1 ? 1 : 0);
console.log(arr); // [1, 2, 3, 3, 4]
我喜欢这个单行道:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
null
或undefined
作为原型
// remove by value. return true if value found and removed, false otherwise
Array.prototype.remove = function(val)
{
return this.includes(val) && !!this.splice(this.indexOf(val), 1);
}
(是的,我读了所有其他的答案 却找不到一个结合的答案)includes
和splice
在同一行中。 )
除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...
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]
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
逻辑上更清洁(容易阅读),更适合使用不可改变状态的编码风格。所以由你决定是否进行这种权衡决定。