Wal*_*ker 7655 javascript arrays
我有一个Numbers数组,我正在使用该.push()
方法向其中添加元素.
有没有一种简单的方法从数组中删除特定元素?相当于像array.remove(number);
.
我必须使用核心的JavaScript - 无框架是不允许的.
Tom*_*ley 10958
找到index
要删除的数组元素,然后删除该索引indexOf
.
splice()方法通过删除现有元素和/或添加新元素来更改数组的内容.
var array = [2, 5, 9];
console.log(array);
var index = array.indexOf(5);
if (index > -1) {
array.splice(index, 1);
}
// array = [2, 9]
console.log(array);
Run Code Online (Sandbox Code Playgroud)
第二个参数splice
是要删除的元素数.请注意,splice
修改数组并返回包含已删除元素的新数组.
Pet*_*son 1154
我不知道你的array.remove(int)
表现如何.我可以想到你可能想要的三种可能性.
要在索引处删除数组的元素i
:
array.splice(i, 1);
Run Code Online (Sandbox Code Playgroud)
如果number
要从数组中删除具有值的每个元素:
for(var i = array.length - 1; i >= 0; i--) {
if(array[i] === number) {
array.splice(i, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想使索引处的元素i
不再存在,但您不希望其他元素的索引发生更改:
delete array[i];
Run Code Online (Sandbox Code Playgroud)
uje*_*tor 1025
在这个代码示例中,我使用"array.filter(...)"函数从数组中删除不需要的项,此函数不会更改原始数组并创建新数组.如果您的浏览器不支持此功能(例如版本9之前的IE或版本1.5之前的Firefox),请考虑使用Mozilla中的过滤器polyfill.
var value = 3
var arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(function(item) {
return item !== value
})
console.log(arr)
// [ 1, 2, 4, 5 ]
Run Code Online (Sandbox Code Playgroud)
let value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
Run Code Online (Sandbox Code Playgroud)
重要事项 ES2015"()=> {}"IE中根本不支持箭头功能语法,Chrome版本为45版本,Firefox版本为22版本,Safari版本为10版本.要在旧浏览器中使用ES2015语法,您可以使用BabelJS
此方法的另一个优点是您可以删除多个项目
let forDeletion = [2, 3, 5]
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => !forDeletion.includes(item))
// !!! Read below about array.includes(...) support !!!
console.log(arr)
// [ 1, 4 ]
Run Code Online (Sandbox Code Playgroud)
重要信息 IE中根本不支持"array.includes(...)"功能,47版本之前的Chrome版本,43版本之前的Firefox版本,9版本之前的Safari版本以及14版本之前的Edge版本所以这里是来自Mozilla的polyfill
// array-lib.js
export function remove(...forDeletion) {
return this.filter(item => !forDeletion.includes(item))
}
// main.js
import { remove } from './array-lib.js'
let arr = [1, 2, 3, 4, 5, 3]
// :: This-Binding Syntax Proposal
// using "remove" function as "virtual method"
// without extending Array.prototype
arr = arr::remove(2, 3, 5)
console.log(arr)
// [ 1, 4 ]
Run Code Online (Sandbox Code Playgroud)
参考
xav*_*m02 424
取决于你是否想留空.
如果你想要一个空插槽,删除就可以了:
delete array[index];
Run Code Online (Sandbox Code Playgroud)
如果不这样做,则应使用拼接方法:
array.splice(index, 1);
Run Code Online (Sandbox Code Playgroud)
如果你需要该项的值,你可以只存储返回的数组的元素:
var value = array.splice(index, 1)[0];
Run Code Online (Sandbox Code Playgroud)
如果您想按某种顺序执行此操作,可以使用array.pop()
最后一个或array.shift()
第一个(并且两者都返回项的值).
如果您不知道该项目的索引,您可以使用array.indexOf(item)
它来获取它(在if()
一个项目中获取一个项目或在一个项目中while()
获取所有项目).array.indexOf(item)
如果未找到,则返回索引或-1.
Ben*_*esh 258
一位朋友在Internet Explorer 8中遇到问题,并向我展示了他的所作所为.我告诉他这是错的,他告诉我他在这里得到了答案.当前的最佳答案不适用于所有浏览器(例如Internet Explorer 8),它只会删除第一次出现的项目.
function remove(arr, item) {
for (var i = arr.length; i--;) {
if (arr[i] === item) {
arr.splice(i, 1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它向后循环遍历数组(因为索引和长度将随着项目的移除而改变)并删除项目(如果已找到).它适用于所有浏览器.
Ran*_*ner 183
过滤器是一种在不改变原始数组的情况下实现它的优雅方法
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]
Run Code Online (Sandbox Code Playgroud)
如果您想实现突变消除行为,您可以使用filter
结果并将其分配给原始数组。
const num = 3;
let arr = [1, 2, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,filter
将删除条件中匹配的所有匹配项(不仅仅是第一次匹配项),如以下示例所示
const num = 3;
let arr = [1, 2, 3, 3, 3, 4];
arr = arr.filter(x => x !== num);
console.log(arr); // [1, 2, 4]
Run Code Online (Sandbox Code Playgroud)
如果您只想删除第一个出现的位置,可以使用splice方法
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]
Run Code Online (Sandbox Code Playgroud)
Sas*_*asa 155
有两种主要方法:
splice():anArray.splice(index, 1);
删除:delete anArray[index];
对数组使用delete时要小心.它有利于删除对象的属性但对数组不太好.最好splice
用于数组.
请记住,当您使用delete
数组时,您可能会得到错误的结果anArray.length
.换句话说,delete
将删除元素但不会更新length属性的值.
使用删除后,您还可能会在索引号中出现漏洞,例如,您最终可能会使用删除之前的索引1,3,4,8,9,11和长度.在这种情况下,所有索引for
循环都会崩溃,因为索引不再是顺序的.
如果delete
由于某种原因被迫使用,那么for each
在需要循环遍历数组时应该使用循环.事实上,如果可能的话,总是避免使用索引for循环.这样,代码将更加健壮,并且不易出现索引问题.
Zir*_*rak 130
Array.prototype.remByVal = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
//Call like
[1, 2, 3, 4].remByVal(3);
Run Code Online (Sandbox Code Playgroud)
Array.prototype.remByVal = function(val) {
for (var i = 0; i < this.length; i++) {
if (this[i] === val) {
this.splice(i, 1);
i--;
}
}
return this;
}
var rooms = ['hello', 'something']
rooms = rooms.remByVal('hello')
console.log(rooms)
Run Code Online (Sandbox Code Playgroud)
slo*_*osd 94
没有必要使用indexOf
或splice
.但是,如果您只想删除一个元素,它会表现得更好.
查找并移动(移动):
function move(arr, val) {
var j = 0;
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] !== val) {
arr[j++] = arr[i];
}
}
arr.length = j;
}
Run Code Online (Sandbox Code Playgroud)
使用indexOf
和splice
(indexof):
function indexof(arr, val) {
var i;
while ((i = arr.indexOf(val)) != -1) {
arr.splice(i, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
仅使用splice
(拼接):
function splice(arr, val) {
for (var i = arr.length; i--;) {
if (arr[i] === val) {
arr.splice(i, 1);
}
}
}
Run Code Online (Sandbox Code Playgroud)
nodejs上运行时间为1000个元素的数组(平均超过10000次运行):
indexof比移动慢约10倍.即使除去调用改进indexOf
的拼接它的性能比更糟糕的举动.
Remove all occurrences:
move 0.0048 ms
indexof 0.0463 ms
splice 0.0359 ms
Remove first occurrence:
move_one 0.0041 ms
indexof_one 0.0021 ms
Run Code Online (Sandbox Code Playgroud)
amd*_*amd 65
太老了回复,但可能通过提供谓词而不是值来帮助某人.
注意:它将更新给定的数组,并返回受影响的行
var removed = helper.removeOne(arr, row => row.id === 5 );
var removed = helper.remove(arr, row => row.name.startsWith('BMW'));
Run Code Online (Sandbox Code Playgroud)
var helper = {
// Remove and return the first occurrence
removeOne: function(array, predicate) {
for (var i = 0; i < array.length; i++) {
if (predicate(array[i])) {
return array.splice(i, 1);
}
}
},
// Remove and return all occurrences
remove: function(array, predicate) {
var removed = [];
for (var i = 0; i < array.length;) {
if (predicate(array[i])) {
removed.push(array.splice(i, 1));
continue;
}
i++;
}
return removed;
}
};
Run Code Online (Sandbox Code Playgroud)
Rog*_*ger 59
John Resig 发布了一个很好的实现:
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
Run Code Online (Sandbox Code Playgroud)
如果您不想扩展全局对象,则可以执行以下操作:
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
Run Code Online (Sandbox Code Playgroud)
但我发布这个的主要原因是警告用户不要使用该页面评论中建议的替代实现(2007年12月14日):
Array.prototype.remove = function(from, to){
this.splice(from, (to=[0,from||1,++to-from][arguments.length])<0?this.length+to:to);
return this.length;
};
Run Code Online (Sandbox Code Playgroud)
它起初似乎运行良好,但是通过一个痛苦的过程我发现它在尝试删除数组中倒数第二个元素时失败了.例如,如果您有一个10个元素的数组,并尝试使用以下方法删除第9个元素:
myArray.remove(8);
Run Code Online (Sandbox Code Playgroud)
你最终得到一个8元素阵列.不知道为什么,但我确认John的原始实现没有这个问题.
Sal*_*ali 59
您可以使用过滤方法轻松完成:
function remove(arrOriginal, elementToRemove){
return arrOriginal.filter(function(el){return el !== elementToRemove});
}
console.log(remove([1, 2, 1, 0, 3, 1, 4], 1));
Run Code Online (Sandbox Code Playgroud)
这将从数组中删除所有元素,并且比slice和indexOf的组合更快地工作
vat*_*sal 59
Underscore.js可用于解决多个浏览器的问题.它使用内置浏览器方法(如果存在).如果它们不存在,就像旧的Internet Explorer版本一样,它使用自己的自定义方法.
从数组中删除元素的简单示例(来自网站):
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 54
今天 (2019-12-09) 我在 macOS v10.13.6 (High Sierra) 上对选定的解决方案进行了性能测试。我展示了delete
(A),但我没有将它与其他方法进行比较,因为它在数组中留下了空白空间。
结论
array.splice
(C)(除了 Safari 用于第二次的小阵列)array.slice+splice
(H) 是 Firefox 和 Safari 最快的不可变解决方案;Array.from
(B) 在 Chrome 中最快在测试中,我以不同的方式从数组中删除中间元素。在A,C的解决方案是原地。的B,d,E,F,G,H的解决方案是不可变的。
具有 10 个元素的数组的结果
在 Chrome 中,array.splice
(C) 是最快的就地解决方案。的array.filter
(d)是最快的不可变的溶液。最慢的是array.slice
(F)。您可以在此处在您的机器上执行测试。
具有 1.000.000 个元素的数组的结果
在 Chrome 中,array.splice
(C) 是最快的就地解决方案(delete
(C) 的速度类似 - 但它在数组中留下了一个空槽(因此它不会执行“完全删除”))。在array.slice-splice
(H)是最快的不可变的溶液。最慢的是array.filter
(D 和 E)。您可以在此处在您的机器上执行测试。
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var log = (letter,array) => console.log(letter, array.join `,`);
function A(array) {
var index = array.indexOf(5);
delete array[index];
log('A', array);
}
function B(array) {
var index = array.indexOf(5);
var arr = Array.from(array);
arr.splice(index, 1)
log('B', arr);
}
function C(array) {
var index = array.indexOf(5);
array.splice(index, 1);
log('C', array);
}
function D(array) {
var arr = array.filter(item => item !== 5)
log('D', arr);
}
function E(array) {
var index = array.indexOf(5);
var arr = array.filter((item, i) => i !== index)
log('E', arr);
}
function F(array) {
var index = array.indexOf(5);
var arr = array.slice(0, index).concat(array.slice(index + 1))
log('F', arr);
}
function G(array) {
var index = array.indexOf(5);
var arr = [...array.slice(0, index), ...array.slice(index + 1)]
log('G', arr);
}
function H(array) {
var index = array.indexOf(5);
var arr = array.slice(0);
arr.splice(index, 1);
log('H', arr);
}
A([...a]);
B([...a]);
C([...a]);
D([...a]);
E([...a]);
F([...a]);
G([...a]);
H([...a]);
Run Code Online (Sandbox Code Playgroud)
This snippet only presents code used in performance tests - it does not perform tests itself.
Run Code Online (Sandbox Code Playgroud)
浏览器对比:Chrome v78.0.0、Safari v13.0.4、Firefox v71.0.0
raj*_*t44 53
您可以使用ES6.
var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);
Run Code Online (Sandbox Code Playgroud)
输出:
["1", "2", "4", "5", "6"]
Run Code Online (Sandbox Code Playgroud)
Lou*_*pax 48
如果要删除删除位置的新数组,可以始终删除特定元素并过滤掉数组.对于没有实现过滤方法的浏览器,可能需要对数组对象进行扩展,但从长远来看,它更容易,因为您所做的只是:
var my_array = [1, 2, 3, 4, 5, 6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));
Run Code Online (Sandbox Code Playgroud)
应该显示 [1, 2, 3, 4, 6]
Ekr*_*que 38
看看这段代码.它适用于所有主流浏览器.
remove_item = function (arr, value) {
var b = '';
for (b in arr) {
if (arr[b] === value) {
arr.splice(b, 1);
break;
}
}
return arr;
}
Run Code Online (Sandbox Code Playgroud)
调用此功能
remove_item(array,value);
Run Code Online (Sandbox Code Playgroud)
M. *_*rog 38
这篇文章总结了自 ECMAScript 2019 (ES10) 起从数组中移除元素的常用方法。
.splice()
| 就地:是 |
| 删除重复项:Yes(loop), No(indexOf) |
| 按值/索引:按索引 |
如果您知道要从数组中删除的值,则可以使用 splice 方法。首先,您必须确定目标项目的索引。然后使用索引作为起始元素并仅删除一个元素。
// With a 'for' loop
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
for( let i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
} // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
// With the .indexOf() method
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
const i = arr.indexOf(5);
arr.splice(i, 1); // => [1, 2, 3, 4, 6, 7, 8, 9, 0]
Run Code Online (Sandbox Code Playgroud)
.filter()
方法删除数组元素| 就地:否 |
| 删除重复项:是 |
| 按价值/指数:按价值 |
通过提供过滤功能,可以从数组中过滤出特定元素。然后为数组中的每个元素调用这样的函数。
const value = 3
let arr = [1, 2, 3, 4, 5, 3]
arr = arr.filter(item => item !== value)
console.log(arr)
// [ 1, 2, 4, 5 ]
Run Code Online (Sandbox Code Playgroud)
Array.prototype
| 就地:是/否(取决于实施)|
| 删除重复项:是/否(取决于实施)|
| 按值/索引:按索引/按值(取决于实现)|
Array 的原型可以使用其他方法进行扩展。然后这些方法可用于创建的数组。
注意:从 JavaScript 标准库(如 Array)扩展对象的原型被一些人认为是一种反模式。
// In-place, removes all, by value implementation
Array.prototype.remove = function(item) {
for (let i = 0; i < this.length; i++) {
if (this[i] === item) {
this.splice(i, 1);
}
}
}
const arr1 = [1,2,3,1];
arr1.remove(1) // arr1 equals [2,3]
// Non-stationary, removes first, by value implementation
Array.prototype.remove = function(item) {
const arr = this.slice();
for (let i = 0; i < this.length; i++) {
if (arr[i] === item) {
arr.splice(i, 1);
return arr;
}
}
return arr;
}
let arr2 = [1,2,3,1];
arr2 = arr2.remove(1) // arr2 equals [2,3,1]
Run Code Online (Sandbox Code Playgroud)
delete
运算符删除数组元素| 就地:是 |
| 删除重复项:否 |
| 按值/索引:按索引 |
使用删除运算符不会影响长度属性。它也不影响后续元素的索引。数组变得稀疏,这是说被删除的项目没有被删除而是变得未定义的一种奇特的方式。
const arr = [1, 2, 3, 4, 5, 6];
delete arr[4]; // Delete element with index 4
console.log( arr ); // [1, 2, 3, 4, undefined, 6]
Run Code Online (Sandbox Code Playgroud)
delete 操作符旨在从 JavaScript 对象中删除属性,数组是对象。
Object
实用程序删除数组元素(>= ES10)| 就地:否 |
| 删除重复项:是 |
| 按价值/指数:按价值 |
ES10 引入了Object.fromEntries
,可用于从任何类似 Array 的对象创建所需的 Array,并在此过程中过滤不需要的元素。
const object = [1,2,3,4];
const valueToRemove = 3;
const arr = Object.values(Object.fromEntries(
Object.entries(object)
.filter(([ key, val ]) => val !== valueToRemove)
));
console.log(arr); // [1,2,4]
Run Code Online (Sandbox Code Playgroud)
length
| 就地:是 |
| 删除重复项:否 |
| 按价值/指数:不适用 |
通过将长度属性设置为小于当前值的值,可以从数组末尾删除 JavaScript 数组元素。任何索引大于或等于新长度的元素都将被删除。
const arr = [1, 2, 3, 4, 5, 6];
arr.length = 5; // Set length to remove element
console.log( arr ); // [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
2.1.2. 使用.pop()
方法
| 就地:是 |
| 删除重复项:否 |
| 按价值/指数:不适用 |
pop 方法移除数组的最后一个元素,返回该元素,并更新 length 属性。pop 方法修改调用它的数组,这意味着与使用 delete 不同的是,最后一个元素被完全删除并减少了数组长度。
const arr = [1, 2, 3, 4, 5, 6];
arr.pop(); // returns 6
console.log( arr ); // [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
| 就地:是 |
| 删除重复项:否 |
| 按价值/指数:不适用 |
该.shift()
方法的工作方式与 pop 方法非常相似,只是它删除 JavaScript 数组的第一个元素而不是最后一个元素。当元素被移除时,剩余的元素被向下移动。
const arr = [1, 2, 3, 4];
arr.shift(); // returns 1
console.log( arr ); // [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
| 就地:是 |
| 删除重复项: N/A |
| 按价值/指数:不适用 |
最快的技术是将数组变量设置为空数组。
let arr = [1];
arr = []; //empty array
Run Code Online (Sandbox Code Playgroud)
可以通过将长度设置为 0 来使用 2.1.1 中的替代技术。
Chu*_*ang 35
你可以使用lodash _.pull(mutate array),_.pullAt(mutate array)或_.without(不要改变数组),
var array1 = ['a', 'b', 'c', 'd']
_.pull(array1, 'c')
console.log(array1) // ['a', 'b', 'd']
var array2 = ['e', 'f', 'g', 'h']
_.pullAt(array2, 0)
console.log(array2) // ['f', 'g', 'h']
var array3 = ['i', 'j', 'k', 'l']
var newArray = _.without(array3, 'i') // ['j', 'k', 'l']
console.log(array3) // ['i', 'j', 'k', 'l']
Run Code Online (Sandbox Code Playgroud)
Ali*_*eza 31
好的,例如你有以下数组:
var num = [1, 2, 3, 4, 5];
Run Code Online (Sandbox Code Playgroud)
我们想删除4号,你可以简单地做下面的代码:
num.splice(num.indexOf(4), 1); // num will be [1, 2, 3, 5];
Run Code Online (Sandbox Code Playgroud)
如果重用此函数,则编写一个可重用的函数,该函数将附加到Native数组函数,如下所示:
Array.prototype.remove = Array.prototype.remove || function(x) {
const i = this.indexOf(x);
if(i===-1)
return;
this.splice(i, 1); // num.remove(5) === [1, 2, 3];
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您使用下面的数组而不是数组中的[5] s,那该怎么办?
var num = [5, 6, 5, 4, 5, 1, 5];
Run Code Online (Sandbox Code Playgroud)
我们需要一个循环来检查所有这些,但更简单,更有效的方法是使用内置的JavaScript函数,所以我们编写一个使用如下所示的过滤器的函数:
const _removeValue = (arr, x) => arr.filter(n => n!==x);
//_removeValue([1, 2, 3, 4, 5, 5, 6, 5], 5) // Return [1, 2, 3, 4, 6]
Run Code Online (Sandbox Code Playgroud)
还有第三方库可以帮助你做这些,比如Lodash或者Underscore,更多信息请看lodash _.pull,_.pullAt或_.without.
Fla*_*pes 30
以下是使用JavaScript从数组中删除项的几种方法.
所描述的所有方法都不会改变原始数组,而是创建一个新数组.
假设您有一个数组,并且想要移除一个位置的项目i
.
一种方法是使用slice()
:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const i = 3
const filteredItems = items.slice(0, i).concat(items.slice(i+1, items.length))
console.log(filteredItems)
Run Code Online (Sandbox Code Playgroud)
slice()
使用它接收的索引创建一个新数组.我们只是创建一个新数组,从开始到我们想要删除的索引,并从我们删除的第一个位置到数组末尾的第一个位置连接另一个数组.
在这种情况下,一个很好的选择是使用filter()
,它提供了更具说明性的方法:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(item => item !== valueToRemove)
console.log(filteredItems)
Run Code Online (Sandbox Code Playgroud)
这使用ES6箭头功能.您可以使用传统功能来支持旧版浏览器:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valueToRemove = 'c'
const filteredItems = items.filter(function(item) {
return item !== valueToRemove
})
console.log(filteredItems)
Run Code Online (Sandbox Code Playgroud)
或者您可以使用Babel并将ES6代码转发回ES5,使其更易于浏览旧浏览器,同时在代码中编写现代JavaScript.
如果不是单个项目,您想要删除多个项目,该怎么办?
让我们找到最简单的解决方案.
您只需创建一个函数并删除系列中的项目:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const removeItem = (items, i) =>
items.slice(0, i-1).concat(items.slice(i, items.length))
let filteredItems = removeItem(items, 3)
filteredItems = removeItem(filteredItems, 5)
//["a", "b", "c", "d"]
console.log(filteredItems)
Run Code Online (Sandbox Code Playgroud)
您可以在回调函数中搜索包含:
const items = ['a', 'b', 'c', 'd', 'e', 'f']
const valuesToRemove = ['c', 'd']
const filteredItems = items.filter(item => !valuesToRemove.includes(item))
// ["a", "b", "e", "f"]
console.log(filteredItems)
Run Code Online (Sandbox Code Playgroud)
splice()
(不要混淆slice()
)改变原始数组,应该避免.
(最初发布于https://flaviocopes.com/how-to-remove-item-from-array/)
小智 27
我是JavaScript的新手,需要这个功能.我只写了这个:
function removeFromArray(array, item, index) {
while((index = array.indexOf(item)) > -1) {
array.splice(index, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当我想使用它时:
//Set-up some dummy data
var dummyObj = {name:"meow"};
var dummyArray = [dummyObj, "item1", "item1", "item2"];
//Remove the dummy data
removeFromArray(dummyArray, dummyObj);
removeFromArray(dummyArray, "item2");
Run Code Online (Sandbox Code Playgroud)
输出 - 正如所料.["item1","item1"]
您可能有不同的需求,因此您可以轻松修改它以适应它们.我希望这可以帮助别人.
Abd*_*UMI 27
const removeByIndex = (list, index) =>
[
...list.slice(0, index),
...list.slice(index + 1)
];
Run Code Online (Sandbox Code Playgroud)
然后 :
removeByIndex([33,22,11,44],1) //=> [33,11,44]
Run Code Online (Sandbox Code Playgroud)
flu*_*rdy 24
如果阵列中有复杂对象,可以使用过滤器吗?在$ .inArray或array.splice不那么容易使用的情况下.特别是如果对象在数组中可能很浅.
例如,如果您有一个带有Id字段的对象,并且您希望从数组中删除该对象:
this.array = this.array.filter(function(element, i) {
return element.id !== idToRemove;
});
Run Code Online (Sandbox Code Playgroud)
kri*_*yaa 24
我想将所有可能的解决方案集中起来,并根据性能对其进行排名。 放在上面的那个比最后一个更受欢迎。
考虑所有方法的基本情况:
let arr = [1, 2, 3, 4, 5];
let elementToRemove = 4;
let indexToRemove = arr.indexOf(elementToRemove);
Run Code Online (Sandbox Code Playgroud)
splice()
方法:【最佳方法/高效】// When you don't know index
arr.splice(indexToRemove,1); // Remove a item at index of elementToRemove
// When you know index
arr.splice(3, 1); // Remove one item at index 3
console.log(arr); // Output: [1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
filter()
方法:【好方法】let filteredArr = arr.filter((num) => num !== elementToRemove);
console.log(filteredArr); // Output: [1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
slice()
方法:[较长的方法(表达式过多) ]let newArr = arr.slice(0, indexToRemove).concat(arr.slice(indexToRemove + 1));
console.log(newArr); // Output: [1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
forEach()
方法:[不推荐,因为它会遍历每个元素]let newArr = [];
arr.forEach((num) => {
if(num !== elementToRemove){
newArr.push(num);
}
});
console.log(newArr); // Output: [1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
zyk*_*lic 23
更新:仅当您不能使用ECMAScript 2015(以前称为ES6)时,才建议使用此方法.如果你可以使用它,这里的其他答案提供了更简洁的实现.
这里的要点将解决您的问题,并删除所有出现的参数而不只是1(或指定的值).
Array.prototype.destroy = function(obj){
// Return null if no objects were found and removed
var destroyed = null;
for(var i = 0; i < this.length; i++){
// Use while-loop to find adjacent equal objects
while(this[i] === obj){
// Remove this[i] and store it within destroyed
destroyed = this.splice(i, 1)[0];
}
}
return destroyed;
}
Run Code Online (Sandbox Code Playgroud)
用法:
var x = [1, 2, 3, 3, true, false, undefined, false];
x.destroy(3); // => 3
x.destroy(false); // => false
x; // => [1, 2, true, undefined]
x.destroy(true); // => true
x.destroy(undefined); // => undefined
x; // => [1, 2]
x.destroy(3); // => null
x; // => [1, 2]
Run Code Online (Sandbox Code Playgroud)
Ame*_*icA 23
我想回答一下2
.假设你有一个如下数组:
let arr = [1,2,3,4];
Run Code Online (Sandbox Code Playgroud)
如果你想删除特殊索引3
,请写下面的代码:
arr.splice(2, 1); //=> arr became [1,2,4]
Run Code Online (Sandbox Code Playgroud)
但是,如果你想删除一个特殊的项目2
,你不知道它的索引如下所示:
arr = arr.filter(e => e !== 3); //=> arr became [1,2,4]
Run Code Online (Sandbox Code Playgroud)
提示:请使用箭头函数进行过滤回调,除非您得到一个空数组.
Tom*_*ski 22
您的问题是关于如何从数组中删除特定项目。通过特定项目,您指的是一个数字,例如。从数组中删除数字 5。据我了解,您正在寻找类似的东西:
// PSEUDOCODE, SCROLL FOR COPY-PASTE CODE
[1,2,3,4,5,6,8,5].remove(5) // result: [1,2,3,4,6,8]
Run Code Online (Sandbox Code Playgroud)
至于 2021 实现它的最佳方法是使用数组过滤器功能:
const input = [1,2,3,4,5,6,8,5];
const removeNumber = 5;
const result = input.filter(
item => item != removeNumber
);
Run Code Online (Sandbox Code Playgroud)
上面的例子使用了array.prototype.filter函数。它遍历所有数组项,只返回那些满足箭头函数的项。因此,旧数组保持不变,而名为 result 的新数组包含所有不等于 5 的项目。你可以自己在线测试。
您可以像这样想象array.prototype.filter 的方式:
代码质量
在这种情况下,Array.filter.prototype 是删除数字的最易读的方法。它几乎不会出现错误并使用核心 JS 功能。
为什么不是array.prototype.map?
Array.prototype.map 有时被认为是该用例的 array.prototype.filter 的替代品。但不应该使用它。原因是array.prototype.filter在概念上是用来过滤满足箭头函数的items(正是我们需要的),而array.prototype.map是用来转换items的。由于我们在迭代时不会更改项目,因此使用的正确函数是 array.prototype.filter。
支持
截至今天(2.12.2020),97,05% 的互联网用户浏览器支持array.prototype.filter。所以一般来说使用是安全的。但是,IE6-8 不支持它。因此,如果您的用例需要支持这些浏览器,那么Chris Ferdinanti 提供了一个很好的polyfill。
表现
Array.prototype.filter 非常适合大多数用例。但是,如果您正在寻找高级数据处理的一些性能改进,您可以探索一些其他选项,例如使用 pure for。另一个不错的选择是重新考虑您正在处理的数组是否必须如此之大,这可能表明 JavaScript 应该从数据源接收减少的数组以进行处理。
Ade*_*ran 21
你永远不应该在你的数组中改变你的数组.因为这是针对功能编程模式的.你可以做的是创建一个新的数组,而不引用你想要使用es6方法更改数据的数组filter
;
var myArray = [1, 2, 3, 4, 5, 6];
Run Code Online (Sandbox Code Playgroud)
假设你想要5
从数组中删除,你可以这样做.
myArray = myArray.filter(value => value !== 5);
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个没有您想要删除的值的新数组.结果将是
[1, 2, 3, 4, 6]; // 5 has been removed from this array
Run Code Online (Sandbox Code Playgroud)
为了进一步理解,您可以阅读Array.filter上的MDN文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
小智 21
不可变和单行方式:
const newArr = targetArr.filter(e => e !== elementToDelete);
Run Code Online (Sandbox Code Playgroud)
bjf*_*her 19
一个更现代的ECMAScript 2015(以前称为Harmony或ES 6)方法.鉴于:
const items = [1, 2, 3, 4];
const index = 2;
Run Code Online (Sandbox Code Playgroud)
然后:
items.filter((x, i) => i !== index);
Run Code Online (Sandbox Code Playgroud)
产量:
[1, 2, 4]
Run Code Online (Sandbox Code Playgroud)
您可以使用Babel和polyfill服务来确保跨浏览器能够很好地支持它.
Max*_*nna 18
从数组中删除特定的元素/字符串可以用一种方法完成: 我仍然认为这是针对这种类型问题可以得到的最优雅的一种方法:
theArray.splice(theArray.indexOf("stringToRemoveFromArray"), 1);
Run Code Online (Sandbox Code Playgroud)
其中 theArray是要从中删除特定内容的数组,stringToRemoveFromArray是要删除的字符串,1是要删除的元素数量。
ori*_*dam 17
我喜欢这种单线:
arr.includes(val) && arr.splice(arr.indexOf(val), 1)
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
(是的,我阅读了所有其他答案,但找不到组合includes
并splice
在同一行中的答案)
Ard*_*rdi 16
基于所有主要正确的答案并考虑到建议的最佳实践(特别是不直接使用Array.prototype),我想出了以下代码:
function arrayWithout(arr, values) {
var isArray = function(canBeArray) {
if (Array.isArray) {
return Array.isArray(canBeArray);
}
return Object.prototype.toString.call(canBeArray) === '[object Array]';
};
var excludedValues = (isArray(values)) ? values : [].slice.call(arguments, 1);
var arrCopy = arr.slice(0);
for (var i = arrCopy.length - 1; i >= 0; i--) {
if (excludedValues.indexOf(arrCopy[i]) > -1) {
arrCopy.splice(i, 1);
}
}
return arrCopy;
}
Run Code Online (Sandbox Code Playgroud)
回顾上述功能,尽管它工作正常,但我意识到可能会有一些性能提升.使用ES6而不是ES5也是一种更好的方法.为此,这是改进的代码:
const arrayWithoutFastest = (() => {
const isArray = canBeArray => ('isArray' in Array)
? Array.isArray(canBeArray)
: Object.prototype.toString.call(canBeArray) === '[object Array]';
let mapIncludes = (map, key) => map.has(key);
let objectIncludes = (obj, key) => key in obj;
let includes;
function arrayWithoutFastest(arr, ...thisArgs) {
let withoutValues = isArray(thisArgs[0]) ? thisArgs[0] : thisArgs;
if (typeof Map !== 'undefined') {
withoutValues = withoutValues.reduce((map, value) => map.set(value, value), new Map());
includes = mapIncludes;
} else {
withoutValues = withoutValues.reduce((map, value) => { map[value] = value; return map; } , {});
includes = objectIncludes;
}
const arrCopy = [];
const length = arr.length;
for (let i = 0; i < length; i++) {
// If value is not in exclude list
if (!includes(withoutValues, arr[i])) {
arrCopy.push(arr[i]);
}
}
return arrCopy;
}
return arrayWithoutFastest;
})();
Run Code Online (Sandbox Code Playgroud)
如何使用:
const arr = [1,2,3,4,5,"name", false];
arrayWithoutFastest(arr, 1); // will return array [2,3,4,5,"name", false]
arrayWithoutFastest(arr, 'name'); // will return [2,3,4,5, false]
arrayWithoutFastest(arr, false); // will return [2,3,4,5]
arrayWithoutFastest(arr,[1,2]); // will return [3,4,5,"name", false];
arrayWithoutFastest(arr, {bar: "foo"}); // will return the same array (new copy)
Run Code Online (Sandbox Code Playgroud)
我目前正在撰写一篇博文,其中我对Array的几个解决方案进行了基准测试,没有出现问题,并比较了运行所需的时间.完成该帖后,我将使用链接更新此答案.只是为了让你知道,我已经将上面的内容与lodash的内容进行了比较,如果浏览器不支持Map
,它就会超过lodash!请注意,我没有使用Array.prototype.indexOf
或Array.prototype.includes
包含exlcudeValues Map
或Object
更快地查询!
wha*_*g28 16
我知道已有很多答案,但其中许多似乎使问题复杂化.这是一种删除键的所有实例的简单递归方法 - 调用self直到找不到索引.是的,它仅适用于浏览器indexOf
,但它很简单,可以轻松填充.
独立功能
function removeAll(array, key){
var index = array.indexOf(key);
if(index === -1) return;
array.splice(index, 1);
removeAll(array,key);
}
Run Code Online (Sandbox Code Playgroud)
原型方法
Array.prototype.removeAll = function(key){
var index = this.indexOf(key);
if(index === -1) return;
this.splice(index, 1);
this.removeAll(key);
}
Run Code Online (Sandbox Code Playgroud)
Thi*_*ath 16
你有1到9个数组,你想删除5使用下面的代码.
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return m !== 5;
});
console.log("new Array, 5 removed", newNumberArray);
Run Code Online (Sandbox Code Playgroud)
如果你想要多个值ex: - 1,7,8
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newNumberArray = numberArray.filter(m => {
return (m !== 1) && (m !== 7) && (m !== 8);
});
console.log("new Array, 1,7 and 8 removed", newNumberArray);
Run Code Online (Sandbox Code Playgroud)
如果要删除数组ex中的数组值: - [3,4,5]
var numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var removebleArray = [3,4,5];
var newNumberArray = numberArray.filter(m => {
return !removebleArray.includes(m);
});
console.log("new Array, [3,4,5] removed", newNumberArray);
Run Code Online (Sandbox Code Playgroud)
包含支持的浏览器是链接
Paw*_*ane 16
有很多方法可以从 Javascript 数组中删除特定元素。以下是我在研究中可以想到的 05 种最佳可用方法。
1.直接使用'splice()'方法
在以下代码段中,特定预定位置的元素从数组中移除。
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + arr);
var removed = arr.splice(4, 2);
console.log("Modified array: " + arr);
console.log("Elements removed: " + removed);
Run Code Online (Sandbox Code Playgroud)
2.使用'splice()'方法按'值'删除元素
在以下代码段中,我们可以使用 for 循环内的 if 条件删除等于预定值的所有元素(例如:所有等于值 6 的元素)。
var arr = [1, 2, 6, 3, 2, 6, 7, 8, 9, 10];
console.log("Original array: " + arr);
for (var i = 0; i < arr.length; i++) {
if (arr[i] === 6) {
var removed = arr.splice(i, 1);
i--;
}
}
console.log("Modified array: " + arr); // 6 is removed
console.log("Removed elements: " + removed);
Run Code Online (Sandbox Code Playgroud)
3.使用'filter()'方法删除按值选择的元素
类似于使用 'splice()' 方法的实现,但它不是改变现有数组,而是创建一个新的元素数组,并删除了不需要的元素。
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filtered = array.filter(function(value, index, arr) {
return value != 6 ;
});
console.log("Original array: "+array);
console.log("New array created: "+filtered); // 6 is removed
Run Code Online (Sandbox Code Playgroud)
4. 使用'Lodash' Javascript 库中的'remove()' 方法
在以下代码段中,Javascript 库中有一个名为“Lodash”的 remove() 方法。此方法也类似于过滤器方法。
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log("Original array: " + array);
var removeElement = _.remove(array, function(n) {
return n === 6;
});
console.log("Modified array: " + array);
console.log("Removed elements: " + removeElement); // 6 is removed
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
5. 制作自定义移除方法
JavaScript 中没有原生的 'array.remove' 方法,但我们可以使用上述方法创建一个方法,我们在以下代码片段中实现了该方法。
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function arrayRemove(arr, value) {
return arr.filter(function(element) {
return element != value;
});
}
console.log("Original array: " + array);
console.log("Modified array: " + arrayRemove(array, 6)); // 6 is removed
Run Code Online (Sandbox Code Playgroud)
最后一种方法(编号 05)更适合解决上述问题。
我想用我们可以用来从数组中删除元素的简单方法来回答。非常感谢您提供宝贵的反馈和意见,以改进我的回答。
小智 16
使用数组过滤方法
let array= [1,2,3,4,511,34,511,78,88];
let value = 511;
array = array.filter(element => element !== value);
console.log(array)
Run Code Online (Sandbox Code Playgroud)
Jef*_*oel 15
如果元素有多个实例,则可以执行向后循环以确保不会搞砸索引.
var myElement = "chocolate";
var myArray = ['chocolate', 'poptart', 'poptart', 'poptart', 'chocolate', 'poptart', 'poptart', 'chocolate'];
/* Important code */
for (var i = myArray.length - 1; i >= 0; i--) {
if (myArray[i] == myElement) myArray.splice(i, 1);
}
Run Code Online (Sandbox Code Playgroud)
Ara*_*yan 15
我有另一个很好的解决方案从数组中删除:
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
小智 15
了解这个:
您可以使用 JavaScript 数组对值进行分组并迭代它们。可以通过多种方式添加和删除数组项。总共有 9 种方法(使用适合您的任何一种)。JavaScript 数组有多种方法可以清理数组值,而不是删除方法。
执行此操作的不同技术方法:
您可以使用它通过以下方式从 JavaScript 数组中删除元素:
1-pop: 从数组末尾删除。
2-shift: 从数组的开头删除。
3-splice: 从特定数组索引中删除。
4- 过滤器: 这允许您以编程方式从数组中删除元素。
方法 1:从 JavaScript 数组的开头删除元素
var ar = ['zero', 'one', 'two', 'three'];
ar.shift(); // returns "zero"
console.log( ar ); // ["one", "two", "three"]
Run Code Online (Sandbox Code Playgroud)
方法 2:从 JavaScript 数组末尾删除元素
var ar = [1, 2, 3, 4, 5, 6];
ar.length = 4; // set length to remove elements
console.log( ar ); // [1, 2, 3, 4]
var ar = [1, 2, 3, 4, 5, 6];
ar.pop(); // returns 6
console.log( ar ); // [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
方法三:在 JavaScript 中使用 Splice 删除数组元素
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var removed = arr.splice(2,2);
console.log(arr);
var list = ["bar", "baz", "foo", "qux"];
list.splice(0, 2);
console.log(list);
Run Code Online (Sandbox Code Playgroud)
方法 4:使用 Splice 按值删除数组项
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for( var i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
}
}
//=> [1, 2, 3, 4, 6, 7, 8, 9, 10]
var arr = [1, 2, 3, 4, 5, 5, 6, 7, 8, 5, 9, 10];
for( var i = 0; i < arr.length; i++){
if ( arr[i] === 5) {
arr.splice(i, 1);
i--;
}
}
//=> [1, 2, 3, 4, 6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
方法5:使用数组过滤方法按值删除项目
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var filtered = array.filter(function(value, index, arr){
return value > 5;
});
//filtered => [6, 7, 8, 9]
//array => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
方法六: Lodash数组删除方法
var array = [1, 2, 3, 4];
var evens = _.remove(array, function(n) {
return n % 2 === 0;
});
console.log(array);// => [1, 3]console.log(evens);// => [2, 4]
Run Code Online (Sandbox Code Playgroud)
方法7:制作一个删除方法
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function arrayRemove(arr, value) {
return arr.filter(function(ele){
return ele != value;
});
}
var result = arrayRemove(array, 6); // result = [1, 2, 3, 4, 5, 7, 8, 9, 10]
Run Code Online (Sandbox Code Playgroud)
方法 8:使用删除运算符显式删除数组元素
var ar = [1, 2, 3, 4, 5, 6];
delete ar[4]; // delete element with index 4
console.log( ar ); // [1, 2, 3, 4, undefined, 6]
alert( ar ); // 1,2,3,4,,6
Run Code Online (Sandbox Code Playgroud)
方法 9:清除或重置 JavaScript 数组
var ar = [1, 2, 3, 4, 5, 6];
//do stuffar = [];
//a new, empty array!
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1;
// Reference arr1 by another variable arr1 = [];
console.log(arr2);
// Output [1, 2, 3, 4, 5, 6]
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = arr1;
// Reference arr1 by another variable arr1 = [];
console.log(arr2);
// Output [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
通过删除 JavaScript 数组项来管理数据至关重要。尽管没有单一的“删除”功能,但您可以使用多种方式和策略清除不需要的数组元素。
小智 14
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');
Run Code Online (Sandbox Code Playgroud)
nsa*_*ana 14
按索引删除
返回没有索引元素的数组副本的函数.
/**
* removeByIndex
* @param {Array} array
* @param {Number} index
*/
function removeByIndex(array, index){
return array.filter(function(elem, _index){
return index != _index;
});
}
l = [1,3,4,5,6,7];
console.log(removeByIndex(l, 1));
$> [ 1, 4, 5, 6, 7 ]
Run Code Online (Sandbox Code Playgroud)
按值删除
返回没有Value的数组副本的函数.
/**
* removeByValue
* @param {Array} array
* @param {Number} value
*/
function removeByValue(array, value){
return array.filter(function(elem, _index){
return value != elem;
});
}
l = [1,3,4,5,6,7];
console.log(removeByValue(l, 5));
$> [ 1, 3, 4, 6, 7]
Run Code Online (Sandbox Code Playgroud)
Ahm*_*mad 14
使用 ES6 扩展运算符从数组中删除元素的不可变方法。
假设您要删除 4。
let array = [1,2,3,4,5]
const index = array.indexOf(4)
let new_array = [...array.slice(0,index), ...array.slice(index+1, array.length)]
console.log(new_array)
=> [1, 2, 3, 5]
Run Code Online (Sandbox Code Playgroud)
mik*_*ent 12
你有一个整数数组,而不是一个键是这些整数的字符串等价物的对象,真是太可惜了。
我已经浏览了很多这些答案,据我所知,它们似乎都在使用“蛮力”。我没有检查每一个,如果不是这样,请道歉。对于较小的数组,这很好,但是如果其中有 000 个整数呢?
如果我错了,请纠正我,但我们不能假设在key => value
地图中,像 JavaScript 对象那样,可以假设密钥检索机制是高度工程化和优化的吗?(注意:如果一些超级专家告诉我事实并非如此,我可以建议改用 ECMAScript 6 的Map 类,这肯定会)。
我只是建议,在某些情况下,最好的解决方案可能是将数组转换为对象……当然,问题在于您可能有重复的整数值。我建议将它们放在桶中作为key => value
条目的“值”部分。(注意:如果您确定没有任何重复的数组元素,这可以简单得多:值“与”键相同,只需Object.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 );
Run Code Online (Sandbox Code Playgroud)
输出:
然后很容易删除所有数字55。
delete myIntsMapObj[ 55 ]; // Again, although keys are strings this works
Run Code Online (Sandbox Code Playgroud)
您不必全部删除它们:索引值按出现的顺序推送到它们的存储桶中,因此(例如):
myIntsMapObj[ 55 ].shift(); // And
myIntsMapObj[ 55 ].pop();
Run Code Online (Sandbox Code Playgroud)
将分别删除第一次和最后一次出现。您可以轻松计算出现频率,通过将一个桶的内容转移到另一个桶等,将所有 55 秒替换为 3 秒。
int
从您的“存储桶对象”中检索修改后的数组稍微涉及但不是那么多:每个存储桶包含由 ( string
) 键表示的值的索引(在原始数组中)。这些存储桶值中的每一个也是唯一的(每个都是原始数组中的唯一索引值):因此您将它们转换为新对象中的键,并将“整数字符串键”中的(实)整数作为值...然后对键进行排序并开始Object.values( ... )
。
这听起来非常复杂且耗时……但显然一切都取决于环境和所需的用途。我的理解是 JavaScript 的所有版本和上下文仅在一个线程中运行,并且该线程不会“放手”,因此“蛮力”方法可能会出现一些可怕的拥塞:不是由indexOf
操作引起的,但多次重复slice
/splice
操作。
附录 如果您确定这对于您的用例来说工程量太大,那么最简单的“蛮力”方法肯定是
const arr = [ 1, 2, 3, 66, 8, 2, 3, 2 ];
const newArray = arr.filter( number => number !== 3 );
console.log( newArray )
Run Code Online (Sandbox Code Playgroud)
(是的,其他答案已经发现Array.prototype.filter
......)
Ask*_*ker 12
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')
Run Code Online (Sandbox Code Playgroud)
在我的机器上,splice
速度更快。这是有道理的,因为splice
仅编辑现有数组,而filter
创建新数组。
也就是说,filter
在逻辑上更清晰(更容易阅读)并且更适合使用不可变状态的编码风格。因此,是否要进行权衡取决于您。
Emm*_*nah 12
(function removeFromArrayPolyfill() {
if (window.Array.prototype.remove) return;
Array.prototype.remove = function (value) {
if (!this.length || !value) return;
const indexOfValue = this.indexOf(value);
if (indexOfValue >= 0) {
this.splice(indexOfValue, 1);
}
};
})();
// testing polyfill
const nums = [10, 20, 30];
nums.remove(20);
console.log(nums);//[10,30]
Run Code Online (Sandbox Code Playgroud)
Ali*_*aza 12
从数组中删除项目的最佳方法是使用过滤方法。
.filter()
返回一个没有过滤项的新数组。
items = items.filter(e => e.id !== item.id);
Run Code Online (Sandbox Code Playgroud)
此.filter()
方法映射到完整的数组,当我返回真实条件时,它将当前项推送到过滤后的数组。在此处阅读有关过滤器的 更多信息。
Enr*_*ico 11
创建新数组:
var my_array = new Array();
Run Code Online (Sandbox Code Playgroud)
向此数组添加元素:
my_array.push("element1");
Run Code Online (Sandbox Code Playgroud)
函数indexOf(返回索引或未找到时为-1):
var indexOf = function(needle)
{
if (typeof Array.prototype.indexOf === 'function') // Newer browsers
{
indexOf = Array.prototype.indexOf;
}
else // Older browsers
{
indexOf = function(needle)
{
var index = -1;
for (var i = 0; i < this.length; i++)
{
if (this[i] === needle)
{
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
Run Code Online (Sandbox Code Playgroud)
检查此元素的索引(使用firefox和IE8 +测试):
var index = indexOf.call(my_array, "element1");
Run Code Online (Sandbox Code Playgroud)
从数组中删除位于索引处的1个元素
my_array.splice(index, 1);
Run Code Online (Sandbox Code Playgroud)
hai*_*ong 11
我发布了删除数组元素的代码,并减少了数组长度。
function removeElement(idx, arr) {
// Check the index value
if (idx < 0 || idx >= arr.length) {
return;
}
// Shift the elements
for (var i = idx; i > 0; --i) {
arr[i] = arr[i - 1];
}
// Remove the first element in array
arr.shift();
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*ish 11
拼接、过滤和删除以从数组中删除元素
每个数组都有它的索引,它有助于删除带有索引的特定元素。
splice() 方法
array.splice(index, 1);
Run Code Online (Sandbox Code Playgroud)
第一个参数是索引,第二个参数是要从该索引中删除的元素数。
所以对于单个元素,我们使用 1。
删除方法
delete array[index]
Run Code Online (Sandbox Code Playgroud)
过滤器()方法
如果要删除数组中重复的元素,请过滤数组:
removeAll = array.filter(e => e != elem);
Run Code Online (Sandbox Code Playgroud)
elem
您要从数组中删除的元素在哪里,array
是您的数组名称。
Kam*_*ski 11
非就地解决方案
arr.slice(0,i).concat(arr.slice(i+1));
Run Code Online (Sandbox Code Playgroud)
arr.slice(0,i).concat(arr.slice(i+1));
Run Code Online (Sandbox Code Playgroud)
Tay*_*kes 11
要从字符串数组中查找并删除特定字符串:
var colors = ["red","blue","car","green"];
var carIndex = colors.indexOf("car"); // Get "car" index
// Remove car from the colors array
colors.splice(carIndex, 1); // colors = ["red", "blue", "green"]
Run Code Online (Sandbox Code Playgroud)
来源:https : //www.codegrepper.com/?search_term=remove+a+particular+element+from+array
Mes*_*Qin 11
仅删除34
年龄中的第一个,而不是所有年龄34
:
ages.splice(ages.indexOf(34), 1);
Run Code Online (Sandbox Code Playgroud)
或者你可以全局定义一个方法:
function remove(array, item){
let ind = array.indexOf(item);
if(ind !== -1)
array.splice(ind, 1);
}
Run Code Online (Sandbox Code Playgroud)
为了删除所有年龄34
:
ages = ages.filter(a => a !== 34);
Run Code Online (Sandbox Code Playgroud)
Nul*_*ter 10
我还遇到了必须从中删除元素的情况Array
..indexOf
没有工作,IE*
所以分享我的工作jQuery.inArray()
解决方案.
var index = jQuery.inArray(val,arr);
if (index > -1) {
arr.splice(index, 1);
//console.log(arr);
}
Run Code Online (Sandbox Code Playgroud)
小智 10
var array = [2, 5, 9];
var res = array.splice(array.findIndex(x => x==5), 1);
console.log(res)
Run Code Online (Sandbox Code Playgroud)
使用 Array.findindex,我们可以减少代码行数。
小智 10
__proto__
您可以使用JavaScript标准并定义此函数。例如,
let data = [];
data.__proto__.remove = (n) => { data = data.flatMap((v) => { return v !== n ? v : []; }) };
data = [1, 2, 3];
data.remove(2);
console.log(data); // [1,3]
data = ['a','b','c'];
data.remove('b');
console.log(data); // [a,c]
Run Code Online (Sandbox Code Playgroud)
Sah*_*mar 10
const array = [1,2,3,4,5,6,7,8,9,0];
const index = array.indexOf(5);
// find Index of specific number
if(index != -1){
array.splice(index, 1); // remove number using index
}
console.log(array);
Run Code Online (Sandbox Code Playgroud)
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6];
array = array.filter(number=> number !== 5);
console.log(array);
Run Code Online (Sandbox Code Playgroud)
使用连接和拆分
let array = [1, 2, 3, 4, 5, 1, 7, 8, 9, 2, 3, 4, 5, 6]
array = Array.from(array.join("-").split("-5-").join("-").split("-"),Number)
console.log(array)
Run Code Online (Sandbox Code Playgroud)
我认为很多JavaScript指令都没有经过深思熟虑的函数式编程.Splice返回已删除的元素,大多数时候您需要减少的数组.这是不好的.
想象一下,你正在做一个递归调用,并且必须传递一个少一项的数组,可能没有当前的索引项.或者想象你正在进行另一个递归调用,并且必须传递一个带有元素的数组.
在这些情况下你都不能做myRecursiveFunction(myArr.push(c))
或myRecursiveFunction(myArr.splice(i,1))
.第一个白痴实际上将传递数组的长度,第二个白痴将传递已删除的元素作为参数.
所以我实际上做了...为了删除一个数组元素并将结果作为参数传递给一个函数同时我做如下
myRecursiveFunction(myArr.slice(0,i).concat(a.slice(i+1)))
Run Code Online (Sandbox Code Playgroud)
当谈到推动那更傻......我喜欢,
myRecursiveFunction((myArr.push(c),myArr))
Run Code Online (Sandbox Code Playgroud)
我相信一个正确的函数式语言,一个方法变异它所调用的对象必须返回对该对象的引用作为结果.
/**
* Removes one instance of `value` from `array`, without mutating the original array. Uses loose comparison.
*
* @param {Array} array Array to remove value from
* @param {*} value Value to remove
* @returns {Array} Array with `value` removed
*/
export function arrayRemove(array, value) {
for(let i=0; i<array.length; ++i) {
if(array[i] == value) {
let copy = [...array];
copy.splice(i, 1);
return copy;
}
}
return array;
}
Run Code Online (Sandbox Code Playgroud)
2017年5月8日
大多数给定的答案适用于严格比较,这意味着两个对象都引用内存中的完全相同的对象(或者是基本类型),但通常要从具有特定值的数组中删除非基本对象.例如,如果您调用服务器并希望针对本地对象检查检索到的对象.
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}]
Run Code Online (Sandbox Code Playgroud)
valuesAreEqual有替代/更快的实现,但这可以完成工作.如果要检查特定字段(例如,某些检索到的UUID与本地UUID),您还可以使用自定义比较器.
另请注意,这是一个功能操作,这意味着它不会改变原始数组.
我发现这篇博客文章展示了九种方法:
从 JavaScript 数组中删除元素的 9 种方法 - 以及如何安全地清除 JavaScript 数组
我更喜欢使用filter()
:
var filtered_arr = arr.filter(function(ele){
return ele != value;
})
Run Code Online (Sandbox Code Playgroud)
在 ES6 中,Set集合提供了一个delete方法,可以从数组中删除特定的值,然后通过扩展运算符将 Set 集合转换为数组。
function deleteItem(list, val) {
const set = new Set(list);
set.delete(val);
return [...set];
}
const letters = ['A', 'B', 'C', 'D', 'E'];
console.log(deleteItem(letters, 'C')); // ['A', 'B', 'D', 'E']
Run Code Online (Sandbox Code Playgroud)
如果您使用的是现代浏览器,则可以使用 .filter。
Array.prototype.remove = function(x){
return this.filter(function(v){
return v !== x;
});
};
var a = ["a","b","c"];
var b = a.remove('a');
Run Code Online (Sandbox Code Playgroud)
my_array.splice(idx, 1) for ele, idx in my_array when ele is this_value
Run Code Online (Sandbox Code Playgroud)
小智 8
使用索引和拼接删除值!
function removeArrValue(arr,value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
return arr;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
虽然以前的大多数答案都回答了这个问题,但尚不清楚为什么slice()
没有使用该方法。是的,filter()
符合不变性标准,但如何做以下更短的等价物?
const myArray = [1,2,3,4];
Run Code Online (Sandbox Code Playgroud)
现在让我们说我们应该从数组中删除第二个元素,我们可以简单地做:
const newArray = myArray.slice(0, 1).concat(myArray.slice(2, 4));
// [1,3,4]
Run Code Online (Sandbox Code Playgroud)
由于其简单和不可变的性质,这种从数组中删除元素的方法今天在社区中受到强烈鼓励。一般来说,应该避免引起突变的方法。例如,我们鼓励你更换push()
用concat()
和splice()
用slice()
。
我做了一个功能:
function pop(valuetoremove, myarray) {
var indexofmyvalue = myarray.indexOf(valuetoremove);
myarray.splice(indexofmyvalue, 1);
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
pop(valuetoremove, myarray);
Run Code Online (Sandbox Code Playgroud)
删除最后一个元素
arrName.pop();
Run Code Online (Sandbox Code Playgroud)
首先删除一个元素
arrName.shift();
Run Code Online (Sandbox Code Playgroud)
从中间删除
arrName.splice(starting index, number of element you wnt to delete);
Example: arrName.splice(1, 1);
Run Code Online (Sandbox Code Playgroud)
删除最后一个元素
arrName.splice(-1);
Run Code Online (Sandbox Code Playgroud)
使用数组索引号删除
delete arrName[1];
Run Code Online (Sandbox Code Playgroud)
通常,最好使用该filter
函数创建一个新数组。
let array = [1,2,3,4];
array = array.filter(i => i !== 4); // [1,2,3]
Run Code Online (Sandbox Code Playgroud)
这也提高了可读性恕我直言。我不喜欢slice
,尽管它知道有时您应该这样做。
小智 8
您可以使用所有访问器示例创建索引:
<div >
</div>
Run Code Online (Sandbox Code Playgroud)
<div >
</div>
Run Code Online (Sandbox Code Playgroud)
function getIndex($id){
return (
this.removeIndex($id)
alert("This element was removed")
)
}
function removeIndex(){
const index = $id;
this.accesor.id.splice(index.id) // You can use splice for slice index on
// accessor id and return with message
}
Run Code Online (Sandbox Code Playgroud)
这里的大多数答案都使用 -
for loop
尽管所有解决方案都应该使用这些方法,但我认为我们可以使用字符串操作。
关于此解决方案的注意事项 -
诀窍是——
stringify
输入数据集和搜索值split
分隔符上的数据,
。 remove = (input, value) => {
const stringVal = JSON.stringify(value);
const result = JSON.stringify(input)
return result.replace(stringVal, "").split(",");
}
Run Code Online (Sandbox Code Playgroud)
这里创建了一个带有对象和数字测试的 JSFiddle - https://jsfiddle.net/4t7zhkce/33/
检查remove
小提琴中的方法。
您可以使用splice
从数组中删除对象或值。
让我们考虑一个长度5
为10
, 20
, 30
, 40
,50
的数组,我想从中删除该值30
。
var array = [10,20,30,40,50];
if (array.indexOf(30) > -1) {
array.splice(array.indexOf(30), 1);
}
console.log(array); // [10,20,40,50]
Run Code Online (Sandbox Code Playgroud)
如果数组包含重复值并且您想删除目标的所有出现,那么这是要走的路...
let data = [2, 5, 9, 2, 8, 5, 9, 5];
let target = 5;
data = data.filter(da => da !== target);
Run Code Online (Sandbox Code Playgroud)
注意: - 过滤器不会改变原始数组;相反,它会创建一个新数组。
所以重新分配很重要。
这导致了另一个问题。你不能做变量const
。它应该是let
或var
。
最简单的方法可能是使用过滤器功能。下面是一个例子:
let array = ["hello", "world"]
let newarray = array.filter(item => item !== "hello");
console.log(newarray);
// ["world"]
Run Code Online (Sandbox Code Playgroud)
小智 8
const arr = [1, 2, 3, 4, 5]
console.log(arr) // [ 1, 2, 3, 4, 5 ]
Run Code Online (Sandbox Code Playgroud)
假设您想从 arr 中删除数字 3。
const newArr = arr.filter(w => w !==3)
console.log(newArr) // [ 1, 2, 4, 5 ]
Run Code Online (Sandbox Code Playgroud)
小智 7
使用jQuery的InArray:
A = [1, 2, 3, 4, 5, 6];
A.splice($.inArray(3, A), 1);
//It will return A=[1, 2, 4, 5, 6]`
Run Code Online (Sandbox Code Playgroud)
注意:如果找不到元素,inArray将返回-1.
删除最后一次出现或所有出现,还是第一次出现?
var array = [2, 5, 9, 5];
// Remove last occurrence (or all occurrences)
for (var i = array.length; i--;) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Remove this line to remove all occurrences
}
}
Run Code Online (Sandbox Code Playgroud)
或者
var array = [2, 5, 9, 5];
// Remove first occurrence
for (var i = 0; array.length; i++) {
if (array[i] === 5) {
array.splice(i, 1);
break; // Do not remove this line
}
}
Run Code Online (Sandbox Code Playgroud)
var y = [1, 2, 3, 9, 4]
var removeItem = 9;
y = jQuery.grep(y, function(value) {
return value != removeItem;
});
console.log(y)
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
对于任何希望复制一个将返回一个删除了重复数字或字符串的新数组的方法的人来说,这是从现有答案中汇总的:
function uniq(array) {
var len = array.length;
var dupFree = [];
var tempObj = {};
for (var i = 0; i < len; i++) {
tempObj[array[i]] = 0;
}
console.log(tempObj);
for (var i in tempObj) {
var element = i;
if (i.match(/\d/)) {
element = Number(i);
}
dupFree.push(element);
}
return dupFree;
}
Run Code Online (Sandbox Code Playgroud)
您的问题没有表明顺序或不同的值是否是一项要求。
如果您不关心顺序,并且不会在容器中多次使用相同的值,请使用 Set。它会更快,更简洁。
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
Run Code Online (Sandbox Code Playgroud)
您可以为此创建一个原型。只需传递数组元素和要从数组元素中删除的值:
Array.prototype.removeItem = function(array,val) {
array.forEach((arrayItem,index) => {
if (arrayItem == val) {
array.splice(index, 1);
}
});
return array;
}
var DummyArray = [1, 2, 3, 4, 5, 6];
console.log(DummyArray.removeItem(DummyArray, 3));
Run Code Online (Sandbox Code Playgroud)
您可以添加原型函数来从数组中“删除”元素。
下面的示例演示了当我们知道元素的索引时如何简单地从数组中删除元素。我们在方法中使用它Array.filter
。
Array.prototype.removeByIndex = function(i) {
if(!Number.isInteger(i) || i < 0) {
// i must be an integer
return this;
}
return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.removeByIndex(2);
console.log(a);
console.log(b);
Run Code Online (Sandbox Code Playgroud)
有时我们不知道元素的索引。
Array.prototype.remove = function(i) {
return this.filter(f => f !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.remove(5).remove(null);
console.log(a);
console.log(b);
// It removes all occurrences of searched value
Run Code Online (Sandbox Code Playgroud)
但是,当我们只想删除第一次出现的搜索值时,我们可以Array.indexOf
在函数中使用该方法。
Array.prototype.removeFirst = function(i) {
i = this.indexOf(i);
if(!Number.isInteger(i) || i < 0) {
return this;
}
return this.filter((f, indx) => indx !== i)
}
var a = [5, -89, (2 * 2), "some string", null, false, undefined, 20, null, 5];
var b = a.removeFirst(5).removeFirst(null);
console.log(a);
console.log(b);
Run Code Online (Sandbox Code Playgroud)
有多种方法可以做到这一点,并且\xe2\x80\x99取决于你想要它如何运作。
\n一种方法是使用该splice
方法并从数组中删除该项目:
let array = [1, 2, 3]\narray.splice(1, 1);\nconsole.log(array)\n\n// return [1, 3]\n
Run Code Online (Sandbox Code Playgroud)\n但请确保传递第二个参数,否则最终会删除索引后的整个数组。
\n第二种方法是使用该filter
方法,它的好处是它是不可变的,这意味着您的主数组不会被操纵:
const array = [1, 2, 3];\nconst newArray = array.filter(item => item !== 2)\nconsole.log(newArray)\n\n// return [1, 3]\n
Run Code Online (Sandbox Code Playgroud)\n
小智 7
这是我使用splice方法删除数组中特定数据的简单代码。splice 方法将被赋予两个参数。第一个参数是起始编号,第二个参数是deleteCount。第二个参数用于从第一个参数的值开始删除一些元素。
let arr = [1, 3, 5, 6, 9];
arr.splice(0, 2);
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
您可以迭代每个array
-item,splice
如果它存在于您的中array
.
function destroy(arr, val) {
for (var i = 0; i < arr.length; i++) if (arr[i] === val) arr.splice(i, 1);
return arr;
}
Run Code Online (Sandbox Code Playgroud)
我喜欢这个版本的splice,使用$.inArray
以下值删除元素:
$(document).ready(function(){
var arr = ["C#","Ruby","PHP","C","C++"];
var itemtoRemove = "PHP";
arr.splice($.inArray(itemtoRemove, arr),1);
});
Run Code Online (Sandbox Code Playgroud)
如果您必须支持旧版本的 Internet Explorer,我建议使用以下 polyfill(注意:这不是一个框架)。它是所有现代数组方法(JavaScript 1.8.5 / ECMAScript 5 Array Extras)的 100% 向后兼容替代品,适用于 Internet Explorer 6+、Firefox 1.5+、Chrome、Safari 和 Opera。
https://github.com/plusdude/array-generics
Vanilla JavaScript(ES5.1) - 就地版
浏览器支持:Internet Explorer 9或更高版本(详细的浏览器支持)
/**
* Removes all occurences of the item from the array.
*
* Modifies the array “in place”, i.e. the array passed as an argument
* is modified as opposed to creating a new array. Also returns the modified
* array for your convenience.
*/
function removeInPlace(array, item) {
var foundIndex, fromIndex;
// Look for the item (the item can have multiple indices)
fromIndex = array.length - 1;
foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {
// Remove the item (in place)
array.splice(foundIndex, 1);
// Bookkeeping
fromIndex = foundIndex - 1;
foundIndex = array.lastIndexOf(item, fromIndex);
}
// Return the modified array
return array;
}
Run Code Online (Sandbox Code Playgroud)
Vanilla JavaScript(ES5.1) - 不可变版本
浏览器支持:与地方版中的vanilla JavaScript相同
/**
* Removes all occurences of the item from the array.
*
* Returns a new array with all the items of the original array except
* the specified item.
*/
function remove(array, item) {
var arrayCopy;
arrayCopy = array.slice();
return removeInPlace(arrayCopy, item);
}
Run Code Online (Sandbox Code Playgroud)
香草ES6 - 不可变版
浏览器支持:Chrome 46,Edge 12,Firefox 16,Opera 37,Safari 8(详细的浏览器支持)
/**
* Removes all occurences of the item from the array.
*
* Returns a new array with all the items of the original array except
* the specified item.
*/
function remove(array, item) {
// Copy the array
array = [...array];
// Look for the item (the item can have multiple indices)
let fromIndex = array.length - 1;
let foundIndex = array.lastIndexOf(item, fromIndex);
while (foundIndex !== -1) {
// Remove the item by generating a new array without it
array = [
...array.slice(0, foundIndex),
...array.slice(foundIndex + 1),
];
// Bookkeeping
fromIndex = foundIndex - 1;
foundIndex = array.lastIndexOf(item, fromIndex)
}
// Return the new array
return array;
}
Run Code Online (Sandbox Code Playgroud)
删除索引i处的元素,而不改变原始数组:
/**
* removeElement
* @param {Array} array
* @param {Number} index
*/
function removeElement(array, index) {
return Array.from(array).splice(index, 1);
}
// Another way is
function removeElement(array, index) {
return array.slice(0).splice(index, 1);
}
Run Code Online (Sandbox Code Playgroud)
一个非常幼稚的实现如下:
Array.prototype.remove = function(data) {
const dataIdx = this.indexOf(data)
if(dataIdx >= 0) {
this.splice(dataIdx ,1);
}
return this.length;
}
let a = [1,2,3];
// This will change arr a to [1, 3]
a.remove(2);
Run Code Online (Sandbox Code Playgroud)
我从函数返回数组的长度以符合其他方法,例如Array.prototype.push()
.
function removeSingle(array, element) {
const index = array.indexOf(element)
if (index >= 0) {
array.splice(index, 1)
}
}
Run Code Online (Sandbox Code Playgroud)
这更复杂,以确保算法在 O(N) 时间内运行。
function removeAll(array, element) {
let newLength = 0
for (const elem of array) {
if (elem !== number) {
array[newLength++] = elem
}
}
array.length = newLength
}
Run Code Online (Sandbox Code Playgroud)
array.filter(elem => elem !== number)
Run Code Online (Sandbox Code Playgroud)
小智 6
从数组中删除特定元素可以使用 filter 选项在一行中完成,并且所有浏览器都支持它:https : //caniuse.com/#search=filter%20array
function removeValueFromArray(array, value) {
return array.filter(e => e != value)
}
Run Code Online (Sandbox Code Playgroud)
我在这里测试了这个功能:https : //bit.dev/joshk/jotils/remove-value-from-array/~code#test.ts
小智 6
使用 .indexOf() 和 .splice() - 可变模式
这里有两种情况:
const drinks = [ 'Tea', 'Coffee', 'Milk'];
const id = 1;
const removedDrink = drinks.splice(id, 1);
console.log(removedDrink)
Run Code Online (Sandbox Code Playgroud)
const drinks = ['Tea','Coffee', 'Milk'];
const id = drinks.indexOf('Coffee'); // 1
const removedDrink = drinks.splice(id, 1);
// ["Coffee"]
console.log(removedDrink);
// ["Tea", "Milk"]
console.log(drinks);
Run Code Online (Sandbox Code Playgroud)
使用 .filter() - 不可变模式
您可以考虑的最佳方式是 - 不是“删除”该项目,而是“创建”一个不包含该项目的新数组。所以我们必须找到它,并完全忽略它。
const drinks = ['Tea','Coffee', 'Milk'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink == removedDrink);
console.log("Filtered Drinks Array:"+ filteredDrinks);
console.log("Original Drinks Array:"+ drinks);
Run Code Online (Sandbox Code Playgroud)
小智 6
splice() 函数能够返回数组中的项目以及从特定索引中删除项目/项目
function removeArrayItem(index, array) {
array.splice(index, 1);
return array;
}
let array = [1,2,3,4];
let index = 2;
array = removeArrayItem(index, array);
console.log(array);
Run Code Online (Sandbox Code Playgroud)
最干净的:
var arr = ['1','2','3'];
arr = arr.filter(e => e !== '3');
console.warn(arr);
Run Code Online (Sandbox Code Playgroud)
这也将删除重复项(如果有)。
var index,
input = [1,2,3],
indexToRemove = 1;
integers = [];
for (index in input) {
if (input.hasOwnProperty(index)) {
if (index !== indexToRemove) {
integers.push(result);
}
}
}
input = integers;
Run Code Online (Sandbox Code Playgroud)
此解决方案将采用输入数组,并将在输入中搜索要删除的值。这将遍历整个输入数组,结果将是删除了特定索引的第二个数组整数。然后将整数数组复制回输入数组。
这里有很多很棒的答案,但对我来说,最有效的方法并不是完全从数组中删除我的元素,而是简单地将它的值设置为 null。
这适用于我拥有的大多数情况并且是一个很好的解决方案,因为我稍后将使用该变量并且不希望它消失,现在只是空的。此外,这种方法是完全跨浏览器兼容的。
array.key = null;
Run Code Online (Sandbox Code Playgroud)
以下方法将从数组中删除给定值的所有条目,而无需创建新数组,并且仅进行一次超快速迭代。它适用于古老的Internet Explorer 5.5浏览器:
function removeFromArray(arr, removeValue) {
for (var i = 0, k = 0, len = arr.length >>> 0; i < len; i++) {
if (k > 0)
arr[i - k] = arr[i];
if (arr[i] === removeValue)
k++;
}
for (; k--;)
arr.pop();
}
var a = [0, 1, 0, 2, 0, 3];
document.getElementById('code').innerHTML =
'Initial array [' + a.join(', ') + ']';
//Initial array [0, 1, 0, 2, 0, 3]
removeFromArray(a, 0);
document.getElementById('code').innerHTML +=
'<br>Resulting array [' + a.join(', ') + ']';
//Resulting array [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
<code id="code"></code>
Run Code Online (Sandbox Code Playgroud)
通过我的解决方案,您可以使用纯JavaScript删除数组中的一个或多个项目.不需要另一个JavaScript库.
var myArray = [1,2,3,4,5]; // First array
var removeItem = function(array,value) { // My clear function
if(Array.isArray(value)) { // For multi remove
for(var i = array.length - 1; i >= 0; i--) {
for(var j = value.length - 1; j >= 0; j--) {
if(array[i] === value[j]) {
array.splice(i, 1);
};
}
}
}
else { // For single remove
for(var i = array.length - 1; i >= 0; i--) {
if(array[i] === value) {
array.splice(i, 1);
}
}
}
}
removeItem(myArray,[1,4]); // myArray will be [2,3,5]
Run Code Online (Sandbox Code Playgroud)
我对基础JavaScript数组做了一个相当有效的扩展:
Array.prototype.drop = function(k) {
var valueIndex = this.indexOf(k);
while(valueIndex > -1) {
this.removeAt(valueIndex);
valueIndex = this.indexOf(k);
}
};
Run Code Online (Sandbox Code Playgroud)
我刚刚在Array.prototype
via 上创建了一个polyfill Object.defineProperty
来删除数组中的所需元素,而不会在稍后通过迭代时导致错误for .. in ..
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)
}
Run Code Online (Sandbox Code Playgroud)
删除整数值
var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]
Run Code Online (Sandbox Code Playgroud)
删除字符串值
var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']
Run Code Online (Sandbox Code Playgroud)
删除布尔值
var a = [true, false, true]
a.remove(false)
a // Output => [true, true]
Run Code Online (Sandbox Code Playgroud)
也可以通过此Array.prototype.remove
方法删除数组内的对象.你只需要指定key => value
了的Object
要删除.
删除对象值
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}]
Run Code Online (Sandbox Code Playgroud)
使用 JavaScript 的原型设计功能在数组对象上定义一个名为 remove() 的方法。
使用splice()方法来满足您的要求。
请看看下面的代码。
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 ]
Run Code Online (Sandbox Code Playgroud)
注意:下面是在Node.js REPL上执行的完整示例代码,它描述了 push()、pop()、shift()、unshift() 和 splice() 方法的使用。
> // 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
>
Run Code Online (Sandbox Code Playgroud)
我自己遇到了这个问题(在可以接受替换数组的情况下)并用一个简单的方法解决了它:
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
Run Code Online (Sandbox Code Playgroud)
给上面的片段一些上下文:
self.thingWithItems = {
items: [],
removeItem: function (item) {
var filteredItems = this.items.filter(function (i) {
return i !== item;
});
this.items = filteredItems;
}
};
Run Code Online (Sandbox Code Playgroud)
此解决方案应适用于参考项和值项。至于此解决方案是否适用,这完全取决于您是否需要维护对原始数组的引用。
对我来说越简单越好,正如我们在 2018 年(接近 2019 年)一样,我给你这个(接近于)单行文字来回答最初的问题:
Array.prototype.remove = function (value) {
return this.filter(f => f != value)
}
Run Code Online (Sandbox Code Playgroud)
有用的是您可以在咖喱表达式中使用它,例如:
[1,2,3].remove(2).sort()
Run Code Online (Sandbox Code Playgroud)
要删除特定元素或后续元素,Array.splice()方法效果很好。
splice() 方法通过删除或替换现有元素和/或添加新元素来更改数组的内容,并返回删除的项目。
语法: array.splice(index, deleteCount, item1, ....., itemX)
这index
是强制性的,其余参数是可选的。
例如:
let arr = [1, 2, 3, 4, 5, 6];
arr.splice(2,1);
console.log(arr);
// [1, 2, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
注意: 如果您知道要删除的元素的索引,则可以使用Array.splice()方法。但我们可能还有以下几种情况:
如果您只想删除最后一个元素,可以使用Array.pop()
如果您只想删除第一个元素,可以使用Array.shift()
如果您只知道元素,但不知道元素的位置(或索引),并且想使用Array.filter()方法删除所有匹配的元素:
let arr = [1, 2, 1, 3, 4, 1, 5, 1];
let newArr = arr.filter(function(val){
return val !== 1;
});
//newArr => [2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
或者使用 splice() 方法作为:
let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
for (let i = 0; i < arr.length-1; i++) {
if ( arr[i] === 11) {
arr.splice(i, 1);
}
}
console.log(arr);
// [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)
或者假设我们del
要从数组中删除arr
:
let arr = [1, 2, 3, 4, 5, 6];
let del = 4;
if (arr.indexOf(4) >= 0) {
arr.splice(arr.indexOf(4), 1)
}
Run Code Online (Sandbox Code Playgroud)
或者
let del = 4;
for(var i = arr.length - 1; i >= 0; i--) {
if(arr[i] === del) {
arr.splice(i, 1);
}
}
Run Code Online (Sandbox Code Playgroud)如果您只知道元素但不知道元素的位置(或索引),并且只想使用 splice() 方法删除第一个匹配元素:
let arr = [1, 11, 2, 11, 3, 4, 5, 11, 6, 11];
for (let i = 0; i < arr.length-1; i++) {
if ( arr[i] === 11) {
arr.splice(i, 1);
break;
}
}
console.log(arr);
// [1, 11, 2, 11, 3, 4, 5, 11, 6, 11]
Run Code Online (Sandbox Code Playgroud)此函数从特定位置的数组中删除元素。
array.remove(position);
Array.prototype.remove = function (pos) {
this.splice(pos, 1);
}
var arr = ["a", "b", "c", "d", "e"];
arr.remove(2); // remove "c"
console.log(arr);
Run Code Online (Sandbox Code Playgroud)
如果您不知道要删除的项目的位置,请使用以下命令:
array.erase(element);
Run Code Online (Sandbox Code Playgroud)
array.erase(element);
Run Code Online (Sandbox Code Playgroud)
您只需要按元素或索引过滤:
var num = [5, 6, 5, 4, 5, 1, 5];
var result1 = num.filter((el, index) => el != 5) // for remove all 5
var result2 = num.filter((el, index) => index != 5) // for remove item with index == 5
console.log(result1);
console.log(result2);
Run Code Online (Sandbox Code Playgroud)
小智 5
使用该filter
方法尝试此代码,您可以从数组中删除任何特定项目。
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeItem(arr, value) {
return arr.filter(function (ele) {
return ele !== value;
});
}
console.log(removeItem(arr, 6));
Run Code Online (Sandbox Code Playgroud)
您可以使用 aSet
代替并使用该delete
函数:
const s = Set;
s.add('hello');
s.add('goodbye');
s.delete('hello');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6134352 次 |
最近记录: |