如何从数组中删除一个特定值? 类似 :
array.remove(value);
我必须使用核心核心核心JavaScript。 不允许框架 。
如何从数组中删除一个特定值? 类似 :
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]
其他回答
Array.prototype.removeItem = function(a) {
for (i = 0; i < this.length; i++) {
if (this[i] == a) {
for (i2 = i; i2 < this.length - 1; i2++) {
this[i2] = this[i2 + 1];
}
this.length = this.length - 1
return;
}
}
}
var recentMovies = ['Iron Man', 'Batman', 'Superman', 'Spiderman'];
recentMovies.removeItem('Superman');
function array_remove(arr, index) {
for (let i = index; i < arr.length - 1; i++) {
arr[i] = arr[i + 1];
}
arr.length -= 1;
return arr;
}
my_arr = ['A', 'B', 'C', 'D'];
console.log(array_remove(my_arr, 0));
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)
我本人也有这个问题(在更换阵列是可以接受的情况下),
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;
}
};
此解决方案应该同时使用引用项和值项。 它都取决于您是否需要保持对原始数组的引用, 以判断该解决方案是否适用 。
非就地解决办法
arr.slice(0,i).concat(arr.slice(i+1));
let arr = [10, 20, 30, 40, 50]
let i = 2 ; // position to remove (starting from 0)
let r = arr.slice(0,i).concat(arr.slice(i+1));
console.log(r);