如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
使用 JavaScript 原型特性定义列对象上名为删除() 的方法 。
使用 spolice () 方法满足您的要求 。
请看看下面的代码
Array.prototype.remove = function(item) {
// 'index' will have -1 if 'item' does not exist,
// else it will have the index of the first item found in the array
var index = this.indexOf(item);
if (index > -1) {
// The splice() method is used to add/remove items(s) in the array
this.splice(index, 1);
}
return index;
}
var arr = [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
// Printing array
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)
// Removing 67 (getting its index, i.e. 2)
console.log("Removing 67")
var index = arr.remove(67)
if (index > 0){
console.log("Item 67 found at ", index)
} else {
console.log("Item 67 does not exist in array")
}
// Printing updated array
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4];
console.log(arr)
// ............... Output ................................
// [ 11, 22, 67, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
// Removing 67
// Item 67 found at 2
// [ 11, 22, 45, 61, 89, 34, 12, 7, 8, 3, -1, -4 ]
注:以下是Norde.js REPL上执行的完整示例代码,该代码描述推()、流行()、转移()、非轮档()和交点()方法的使用。
> // Defining an array
undefined
> var arr = [12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34];
undefined
> // Getting length of array
undefined
> arr.length;
16
> // Adding 1 more item at the end i.e. pushing an item
undefined
> arr.push(55);
17
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34, 55 ]
> // Popping item from array (i.e. from end)
undefined
> arr.pop()
55
> arr
[ 12, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Remove item from beginning
undefined
> arr.shift()
12
> arr
[ 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> // Add item(s) at beginning
undefined
> arr.unshift(67); // Add 67 at beginning of the array and return number of items in updated/new array
16
> arr
[ 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.unshift(11, 22); // Adding 2 more items at the beginning of array
18
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> // Define a method on array (temporarily) to remove an item and return the index of removed item; if it is found else return -1
undefined
> Array.prototype.remove = function(item) {
... var index = this.indexOf(item);
... if (index > -1) {
..... this.splice(index, 1); // splice() method is used to add/remove items in array
..... }
... return index;
... }
[Function]
>
> arr
[ 11, 22, 67, 45, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(45); // Remove 45 (you will get the index of removed item)
3
> arr
[ 11, 22, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(22) // Remove 22
1
> arr
[ 11, 67, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
> arr.remove(67) // Remove 67
1
> arr
[ 11, 67, 89, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(89) // Remove 89
2
> arr
[ 11, 67, 34, 12, 7, 8, 3, -1, -4, -11, 0, 56, 12, 34 ]
>
> arr.remove(100); // 100 doesn't exist, remove() will return -1
-1
>
其他回答
ES6且无突变:(2016年10月)
const removeByIndex = (list, index) => [ ...list.slice(0, index), ...list.slice(index + 1) ]; output = removeByIndex([33,22,11,44],1) //=> [33,11,44] console.log(output)
使用.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 (“ 原件饮料阵列 :” +饮料 );
2017-005-08
大多数给定的回答都用于严格的比较, 意思是两个对象在内存( 或原始类型) 中引用完全相同的对象, 但通常您想要从具有一定值的数组中删除一个非原始对象。 例如, 如果您给服务器打电话, 并想要对照本地对象检查已检索到的对象 。
const a = {'field': 2} // Non-primitive object
const b = {'field': 2} // Non-primitive object with same value
const c = a // Non-primitive object that reference the same object as "a"
assert(a !== b) // Don't reference the same item, but have same value
assert(a === c) // Do reference the same item, and have same value (naturally)
//Note: there are many alternative implementations for valuesAreEqual
function valuesAreEqual (x, y) {
return JSON.stringify(x) === JSON.stringify(y)
}
//filter will delete false values
//Thus, we want to return "false" if the item
// we want to delete is equal to the item in the array
function removeFromArray(arr, toDelete){
return arr.filter(target => {return !valuesAreEqual(toDelete, target)})
}
const exampleArray = [a, b, b, c, a, {'field': 2}, {'field': 90}];
const resultArray = removeFromArray(exampleArray, a);
//resultArray = [{'field':90}]
数值AreEqual有替代/更快的操作,但这样可以操作。如果您有特定的字段要检查,也可以使用自定义的比较器(例如,有些已检索的 UUID 相对于本地的 UUID ) 。
2. 还注意到这是一个功能操作,意即它不改变原始阵列。
多可惜,您有数组整数,而不是键是这些整数的字符串等量的对象。
我看过很多这样的答案, 在我看来,它们似乎都使用了“粗力 ” ( 粗力 ) 。 我还没有检查每个答案, 如果不是这样的话, 请道歉。 对于一个小的阵列来说,这很好, 但如果你有千个整数呢?
纠正我,如果我错了, 但我们不能假设在关键值地图中, JavaScript 物体的种类就是 JavaScript 对象, 关键检索机制可以被假定为高度工程化和优化? (NB: 如果一些超级专家告诉我情况并非如此, 我建议使用ECMAScript 6 的地图类, 这当然会是这样 ) 。
我只是建议,在某些情况下,最好的解决方案可能是将您的阵列转换为对象... 当然,问题在于您可能有重复的整数值。 我建议将那些放在桶中作为关键 {} {} 值条目中的“ 价值” 部分。 (NB: 如果您确定您没有重复的阵列元素, 这样可以简单得多 : 值“ 和” 键, 只需去对象. values (...) 就可以返回修改后的阵列 。)
所以,你可以做到这一点:
const arr = [ 1, 2, 55, 3, 2, 4, 55 ];
const f = function( acc, val, currIndex ){
// We have not seen this value before: make a bucket... NB: although val's typeof is 'number',
// there is seamless equivalence between the object key (always string)
// and this variable val.
! ( val in acc ) ? acc[ val ] = []: 0;
// Drop another array index in the bucket
acc[ val ].push( currIndex );
return acc;
}
const myIntsMapObj = arr.reduce( f, {});
console.log( myIntsMapObj );
产出:
对象 [<1个空位>、Array1、Array[2]、Array1、Array1、<5个空位]、46个以上...]
然后很容易删除所有55个数字。
delete myIntsMapObj[ 55 ]; // Again, although keys are strings this works
你不必全部删除: 指数值按外观被挤进桶里, 所以(例如):
myIntsMapObj[ 55 ].shift(); // And
myIntsMapObj[ 55 ].pop();
将分别删除第一次和最后一次发生的情况。 您可以很容易地计算发生频率, 将一个桶的内装物转移到另一个桶等, 将所有55个都替换为3个 。
从您的“ bucket 对象” 中获取修改的整数组略为涉及, 但数量不多 : 每个桶都包含以( 字符串) 键表示的值的索引( 原始数组) 。 这些桶的每一个值也是独一无二的( 每个是原始数组中唯一的索引值 ) : 所以您把它们转换成新对象中的键, 将“ 整数” 中的( 真实) 整数作为值... 然后对键进行排序, 然后对对象. values (...) 排序 。
这听起来很牵强,很费时... 但显然一切都取决于环境 和理想的用法。我的理解是 JavaScript 的所有版本和背景 只能用一条线运作, 这条线不会“放手 ” , 所以可能会有一些可怕的拥堵 , 使用“强力” 方法: 不是由 Enterof 行动造成的, 而是由多个重复的切片/碎块操作造成的。
增编 如果你确定这对你来说太过分工程了 使用这个案子的话 最简单的"强力"方法肯定就是
const arr = [ 1, 2, 3, 66, 8, 2, 3, 2 ];
const newArray = arr.filter( number => number !== 3 );
console.log( newArray )
(是的,其他的答案 已经发现阵列. 原型. 过滤器... )
我对基底 JavaScript 阵列进行了相当高效的扩展:
Array.prototype.drop = function(k) {
var valueIndex = this.indexOf(k);
while(valueIndex > -1) {
this.removeAt(valueIndex);
valueIndex = this.indexOf(k);
}
};