如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
如何从数组中删除一个特定值? 类似 :
array.remove(value);
制约:我必须使用核心 JavaScript 。 框架不允许 。
当前回答
通常比较好用过滤功能创建新阵列。
let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]
这还提高了易读性IMHO。我不是切片的粉丝, 虽然它知道有时你应该去。
其他回答
我刚刚通过对象.defineProperty在 Array. prototype 上创建了一个多填充器, 以便删除一个阵列中想要的元素, 而不会导致在... 的... 。
if (!Array.prototype.remove) {
// Object.definedProperty is used here to avoid problems when iterating with "for .. in .." in Arrays
// https://stackoverflow.com/questions/948358/adding-custom-functions-into-array-prototype
Object.defineProperty(Array.prototype, 'remove', {
value: function () {
if (this == null) {
throw new TypeError('Array.prototype.remove called on null or undefined')
}
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] === 'object') {
if (Object.keys(arguments[i]).length > 1) {
throw new Error('This method does not support more than one key:value pair per object on the arguments')
}
var keyToCompare = Object.keys(arguments[i])[0]
for (var j = 0; j < this.length; j++) {
if (this[j][keyToCompare] === arguments[i][keyToCompare]) {
this.splice(j, 1)
break
}
}
} else {
var index = this.indexOf(arguments[i])
if (index !== -1) {
this.splice(index, 1)
}
}
}
return this
}
})
} else {
var errorMessage = 'DANGER ALERT! Array.prototype.remove has already been defined on this browser. '
errorMessage += 'This may lead to unwanted results when remove() is executed.'
console.log(errorMessage)
}
删除整数值
var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]
删除字符串值
var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']
删除布尔值
var a = [true, false, true]
a.remove(false)
a // Output => [true, true]
也可以通过此 Array. prototype. remove 方法从数组中移除对象。您只需要指定要删除对象的键值 {% 。
删除对象值
var a = [{a: 1, b: 2}, {a: 2, b: 2}, {a: 3, b: 2}]
a.remove({a: 1})
a // Output => [{a: 2, b: 2}, {a: 3, b: 2}]
除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...
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]
使用 JavaScript 从数组中删除一个项的几种方法 。
所描述的所有方法都不改变原始数组,而是创建一个新的数组。
如果您知道某个项目的索引
假设您有一个阵列, 您想要删除位置 i 上的项目 。
一种方法是使用切片( ) :
const items = [a], 'b','c','d','e','f'] const i = 3 const 过滤项目 = items.selice(0, i).concat( items.selice( i+1, items. long)) 控制台.log( 过滤项目)
切片 () 创建新数组, 使用它收到的索引 。 我们只需创建一个新数组, 从开始到要删除的索引, 并且将另一个数组从我们删除后的第一个位置集中到数组的末尾 。
如果您知道数值
在这种情况下,一个很好的选择是使用过滤器(),这提供了一种更宣示性的方法:
Const 项 = [“ a ”、“ b ” 、 “ c ” 、 “ d ” 、 “ e ” 、 “ f ” 、 “ f ” 等值 Toremove = “ c” 等式过滤项目 = 项. filter (项目 项 ! ! ! = ex 值 to remove) 控制台.log (过滤项目 )
此选项使用 ES6 箭头函数。 您可以使用传统函数支持旧的浏览器 :
const items = ['a', 'b','c','d','d','e','f'] const value to remove ='c' const 过滤项目= items. filter(功能(项目) {返回项目!}== value to remove}控制台.log(过滤项目)
或者你可以使用 Babel 将ES6代码转换回ES5, 使旧浏览器更容易消化, 而在您的代码中写入现代 JavaScript 。
删除多个项目
如果不是单项,而是要删除许多项,会怎么样?
让我们找到最简单的解决方案
按指数分列的指数
您可以在序列中创建函数并删除项目 :
const items = [a], b', c', d', d', e', e', e', f'] const demote =( items, i) = items = (items, i, i' i) {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}} {{{{{{{{{{{{{{{{{{{{}}}}}} {{{{{{{{{{{{{{}}}{{{{{{{{{{{{{{}}}}{{{{{{{{{{{{{{{{{{{}}}} {{{{{{{{{{{{{}}}}}{{{{{{{{}}}}}}}{{{{{{{{}}}}}}{{{{{{{{{{{{}}}}}}}}}}}{{{{{{{{{}}}}}}}}}}}}}}}{{{{{}}}}}}}{{}}}}{{{{{}}}}}{{{{{}}}}}}}}}{{{{{{{{{{{{{{{{}}}}}{{{{{{{{{{}}}}}}}}{{{{}}}}{{{{{{{{{{}}}}{}}}}}}}}}{}}}}}}}}}}}}}}}}}}{}}}}}}}}}}}{{}{{}{}{}}}}{{}}}}}}}}}}{}{}{}
以数值计
您可以在回溯函数中搜索包含内容 :
const items = ['a', 'b', 'c','d','d','e','f'] const value to remove = ['c','d'] comst filtems = items. filter(项目 \\\ ? $values to remove.) 包括(项目) // ["a","b","e","f" 控制台。log(过滤项目)
避免突变原始数组
plice() spolice () (不得与切片() 相混淆) 使原始数组变形, 并应避免 。
(最初张贴在我的网站上:https://flaviocopes.com/how-to-remove-itm-from-array/)
spolice () 函数能够将数组中的项目还给您, 从特定的索引中删除项目 / 项 :
函数删除 ArrayText( index, 数组) { 数组. splice( index, 1); 返回数组; } 让数组 = [ 1, 2, 3,4]; 让 index = 2; 数组 = 删除 ArrayText( index, 数组); 控制台. log( 数组);
使用 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
>