如何按值从数组中移除项?

时间:2022-08-26 14:07:11

Is there a method to remove an item from a JavaScript array?

是否有从JavaScript数组中移除项的方法?

Given an array:

给定一个数组:

var ary = ['three', 'seven', 'eleven'];

I would like to do something like:

我想做一些类似的事情:

removeItem('seven', ary);

I've looked into splice() but that only removes by the position number, whereas I need something to remove an item by its value.

我已经研究了splice(),但是它只删除了位置号,而我需要用它的值来删除一个项。

29 个解决方案

#1


371  

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

这可以是一个全局函数或自定义对象的方法,如果您不允许添加到本机原型。它从与任何参数匹配的数组中删除所有项。

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

To make it a global-

让它成为全球性的。

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

并照顾到IE8和以下。

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}

#2


1086  

You can use the indexOf method like this:

你可以使用这样的索引方法:

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

Note: You'll need to shim it for IE8 and below

注意:您将需要为IE8和以下提供shim。

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

console.log(array)

#3


222  

A one-liner will do it,

一行人会做,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

This makes use of the filter function in JS. It's supported in IE9 and up.

这就利用了JS中的filter函数。在IE9和up中都有支持。

What it does (from the doc link)

它的作用(来自doc链接)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

filter()为数组中的每个元素调用一个提供的回调函数,并构造一个新的数组,其中回调返回一个值,该值将强制转换为true。回调仅调用具有指定值的数组的索引;对于已删除或从未被赋值的索引,它不会被调用。不传递回调测试的数组元素被简单地跳过,并且不包含在新数组中。

So basically, this is the same as all the other for (var key in ary) { ... } solutions, except that the for in construct is supported as of IE6.

基本上,这和其他的(var key in ary)是一样的{…}解决方案,除了在构造上支持的是IE6。

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

基本上,过滤器是一种方便的方法,它看起来更好(而且是可链接的),而不是构建(AFAIK)。

#4


118  

You can use underscore.js. It really makes things simple.

您可以使用underscore.js。它真的让事情变得简单。

For example, with this:

例如,用这个:

var result = _.without(['three','seven','eleven'], 'seven');

And result will be ['three','eleven'].

结果将是[' 3 ',' 11 ']。

In your case the code that you will have to write is:

在你的情况下,你需要写的代码是:

ary = _.without(ary, 'seven')

It reduces the code that you write.

它减少了您编写的代码。

#5


40  

Check out this way:

看看这个:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

and in a function:

在一个函数:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');

#6


32  

Here's a version that uses jQuery's inArray function:

这个版本使用了jQuery的inArray函数:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}

#7


22  

var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}

#8


12  

What you're after is filter

你所追求的是过滤器!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

This will allow you to do the following:

这将允许您执行以下操作:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

This was also noted in this thread somewhere else: https://*.com/a/20827100/293492

在这个线程中也注意到了这一点:https://*.com/a/20827100/293492。

#9


8  

Seeing as there isn't a pretty one, here's a simple and reusable ES6 function.

由于没有一个漂亮的函数,这里有一个简单的可重用的ES6函数。

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

Usage:

用法:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')

#10


6  

Removing all matching elements from the array (rather than just the first as seems to be the most common answer here):

从数组中删除所有匹配的元素(而不是第一个似乎是最常见的答案):

while ($.inArray(item, array) > -1) {
    array.splice( $.inArray(item, array), 1 );
}

I used jQuery for the heavy lifting, but you get the idea if you want to go native.

我用jQuery做了繁重的工作,但是如果你想要本地化的话,你就知道了。

#11


6  

a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete:

一个非常干净的解决方案在所有的浏览器中工作,并且没有任何框架,它是一个新的数组,并且简单地返回它没有你想要删除的项目:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}

#12


6  

You can do it with these two ways:

你可以用以下两种方法来做:

var arr = ["1","2","3","4"] // we wanna delete number "3"

first:

第一:

a.splice(a.indexOf('3'),1)

second (ES6):

第二个(ES6):

a = a.filter(e => e !== '3')

#13


4  

indexOf is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).

indexOf是一个选项,但它的实现基本上是搜索整个数组的值,所以执行时间会随着数组的大小而增长。(我想,在每个浏览器中,我只检查了Firefox)。

I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.

我还没有一个IE6来检查,但我认为它是一个安全的赌注,你可以在几乎所有的客户端机器上以这种方式检查至少100万个数组项。如果[数组大小]*[每秒搜索]可能增长超过100万,你应该考虑一个不同的实现。

Basically you can use an object to make an index for your array, like so:

基本上,你可以用一个对象来为你的数组做一个索引,比如:

var index={'three':0, 'seven':1, 'eleven':2};

Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.

任何一个正常的JavaScript环境都会为这些对象创建一个可搜索的索引,这样您就可以快速地将一个键转换为一个值,无论对象有多少属性。

This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.

这只是基本的方法,根据您的需要,您可以组合多个对象和/或数组,以使相同的数据能够快速地搜索不同的属性。如果您指定您的确切需要,我可以建议一个更具体的数据结构。

#14


3  

ES6 way.

ES6方式。

let commentsWithoutDeletedArray = commentsArray.filter( (comment) => !(comment.Id === commentId));

#15


2  

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

诀窍是从头到尾遍历数组,这样就不会在删除元素时搞乱索引。

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]

arr现在是["red", "black", "white"]

#16


1  

Please do not use the variant with delete - it makes a hole in the array as it does not re-index the elements after the deleted item.

请不要使用带有delete的变体——它在数组中创建一个漏洞,因为它不会在删除后重新索引元素。

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]

#17


1  

I used the most voted option and created a function that would clean one array of words using another array of unwanted words:

我使用了最常用的选项,并创建了一个函数,该函数将使用另一组不需要的单词来清除一组单词:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

To use, do the following:

使用方法如下:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)

#18


1  

Non-destructive removal:

非破坏性拆卸:

function removeArrayValue(array, value)
{
    var thisArray = array.slice(0); // copy the array so method is non-destructive

    var idx = thisArray.indexOf(value); // initialise idx

    while(idx != -1)
    {
        thisArray.splice(idx, 1); // chop out element at idx

        idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
    }

    return thisArray;
}

#19


1  

If you have unique values in your array, you can use Set, and it has delete:

如果你的数组中有唯一的值,你可以使用Set,它有delete:

var mySet = new Set(['foo']);
mySet.delete('foo'); // Returns true.  Successfully removed.
mySet.has('foo');    // Returns false. The "foo" element is no longer present.

#20


1  

function removeFrmArr(array, element) {
  return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(a, 3);
// return value like this
//[1, 2, 4, 5]

#21


1  

You can use without or pull from Lodash:

你可以不用或拉出Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]

#22


0  

var remove = function(array, value) {
    var index = null;

    while ((index = array.indexOf(value)) !== -1)
        array.splice(index, 1);

    return array;
};

#23


0  

I tried using the function method from jbaron above but found that I needed to keep the original array intact for use later, and creating a new array like this:

我尝试使用上面的jbaron的函数方法,但发现我需要保留原来的数组,以便以后使用,并创建这样的新数组:

var newArray = referenceArray;

apparently creates by reference instead of value because when I removed an element from newArray the referenceArray also had it removed. So I decided to create a new array each time like this:

显然是由引用而不是值创建的,因为当我从newArray中删除一个元素时,referenceArray也删除了它。所以我决定每次都创建一个新的数组:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

Then I use it like this in another function:

然后我在另一个函数中使用它:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

Now the vesselArr remains intact while each time I execute the above code the otherVessels array includes all but the latest vesselID element.

现在,vesselArr保持完整,而每次执行上面的代码时,其他容器阵列包括了最新的vesselID元素。

#24


0  

CoffeeScript+jQuery variant:

CoffeeScript + jQuery变体:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

it remove only one, not all.

它只除去一个,不是全部。

#25


0  

//This function allows remove even array from array
var removeFromArr = function(arr, elem) { 
    var i, len = arr.length, new_arr = [],
    sort_fn = function (a, b) { return a - b; };
    for (i = 0; i < len; i += 1) {
        if (typeof elem === 'object' && typeof arr[i] === 'object') {
            if (arr[i].toString() === elem.toString()) {
                continue;
            } else {                    
                if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
                    continue;
                }
            }
        }
        if (arr[i] !== elem) {
            new_arr.push(arr[i]);
        }
    }
    return new_arr;
}

Example of using

使用的例子

var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]

var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]

#26


0  

Another variation:

另一个变化:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

It's indexOf() inside a loop again, but on the assumption that the array to remove is small relative to the array to be cleaned; every removal shortens the while loop.

它是在一个循环内的indexOf(),但是假设要清除的数组相对于要清理的数组是小的;每次去除都会缩短while循环。

#27


0  

//edited thanks to MarcoCI for the advice

//感谢MarcoCI的建议。

try this:

试试这个:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

hope this help you

希望这有助于你

#28


0  

let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]

#29


-2  

var ary = ['three', 'seven', 'eleven'];
_.pull(ary, 'seven'); // ['three', 'eleven']
console.log(ary)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>

#1


371  

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

这可以是一个全局函数或自定义对象的方法,如果您不允许添加到本机原型。它从与任何参数匹配的数组中删除所有项。

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

To make it a global-

让它成为全球性的。

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

并照顾到IE8和以下。

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}

#2


1086  

You can use the indexOf method like this:

你可以使用这样的索引方法:

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

Note: You'll need to shim it for IE8 and below

注意:您将需要为IE8和以下提供shim。

var array = [1,2,3,4]
var item = 3

var index = array.indexOf(item);
if (index !== -1) array.splice(index, 1);

console.log(array)

#3


222  

A one-liner will do it,

一行人会做,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

This makes use of the filter function in JS. It's supported in IE9 and up.

这就利用了JS中的filter函数。在IE9和up中都有支持。

What it does (from the doc link)

它的作用(来自doc链接)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

filter()为数组中的每个元素调用一个提供的回调函数,并构造一个新的数组,其中回调返回一个值,该值将强制转换为true。回调仅调用具有指定值的数组的索引;对于已删除或从未被赋值的索引,它不会被调用。不传递回调测试的数组元素被简单地跳过,并且不包含在新数组中。

So basically, this is the same as all the other for (var key in ary) { ... } solutions, except that the for in construct is supported as of IE6.

基本上,这和其他的(var key in ary)是一样的{…}解决方案,除了在构造上支持的是IE6。

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

基本上,过滤器是一种方便的方法,它看起来更好(而且是可链接的),而不是构建(AFAIK)。

#4


118  

You can use underscore.js. It really makes things simple.

您可以使用underscore.js。它真的让事情变得简单。

For example, with this:

例如,用这个:

var result = _.without(['three','seven','eleven'], 'seven');

And result will be ['three','eleven'].

结果将是[' 3 ',' 11 ']。

In your case the code that you will have to write is:

在你的情况下,你需要写的代码是:

ary = _.without(ary, 'seven')

It reduces the code that you write.

它减少了您编写的代码。

#5


40  

Check out this way:

看看这个:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

and in a function:

在一个函数:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');

#6


32  

Here's a version that uses jQuery's inArray function:

这个版本使用了jQuery的inArray函数:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}

#7


22  

var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}

#8


12  

What you're after is filter

你所追求的是过滤器!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

This will allow you to do the following:

这将允许您执行以下操作:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

This was also noted in this thread somewhere else: https://*.com/a/20827100/293492

在这个线程中也注意到了这一点:https://*.com/a/20827100/293492。

#9


8  

Seeing as there isn't a pretty one, here's a simple and reusable ES6 function.

由于没有一个漂亮的函数,这里有一个简单的可重用的ES6函数。

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

Usage:

用法:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')

#10


6  

Removing all matching elements from the array (rather than just the first as seems to be the most common answer here):

从数组中删除所有匹配的元素(而不是第一个似乎是最常见的答案):

while ($.inArray(item, array) > -1) {
    array.splice( $.inArray(item, array), 1 );
}

I used jQuery for the heavy lifting, but you get the idea if you want to go native.

我用jQuery做了繁重的工作,但是如果你想要本地化的话,你就知道了。

#11


6  

a very clean solution working in all browsers and without any framework is to asign a new Array and simply return it without the item you want to delete:

一个非常干净的解决方案在所有的浏览器中工作,并且没有任何框架,它是一个新的数组,并且简单地返回它没有你想要删除的项目:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}

#12


6  

You can do it with these two ways:

你可以用以下两种方法来做:

var arr = ["1","2","3","4"] // we wanna delete number "3"

first:

第一:

a.splice(a.indexOf('3'),1)

second (ES6):

第二个(ES6):

a = a.filter(e => e !== '3')

#13


4  

indexOf is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).

indexOf是一个选项,但它的实现基本上是搜索整个数组的值,所以执行时间会随着数组的大小而增长。(我想,在每个浏览器中,我只检查了Firefox)。

I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.

我还没有一个IE6来检查,但我认为它是一个安全的赌注,你可以在几乎所有的客户端机器上以这种方式检查至少100万个数组项。如果[数组大小]*[每秒搜索]可能增长超过100万,你应该考虑一个不同的实现。

Basically you can use an object to make an index for your array, like so:

基本上,你可以用一个对象来为你的数组做一个索引,比如:

var index={'three':0, 'seven':1, 'eleven':2};

Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.

任何一个正常的JavaScript环境都会为这些对象创建一个可搜索的索引,这样您就可以快速地将一个键转换为一个值,无论对象有多少属性。

This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.

这只是基本的方法,根据您的需要,您可以组合多个对象和/或数组,以使相同的数据能够快速地搜索不同的属性。如果您指定您的确切需要,我可以建议一个更具体的数据结构。

#14


3  

ES6 way.

ES6方式。

let commentsWithoutDeletedArray = commentsArray.filter( (comment) => !(comment.Id === commentId));

#15


2  

The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.

诀窍是从头到尾遍历数组,这样就不会在删除元素时搞乱索引。

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

arr is now ["red", "black", "white"]

arr现在是["red", "black", "white"]

#16


1  

Please do not use the variant with delete - it makes a hole in the array as it does not re-index the elements after the deleted item.

请不要使用带有delete的变体——它在数组中创建一个漏洞,因为它不会在删除后重新索引元素。

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]

#17


1  

I used the most voted option and created a function that would clean one array of words using another array of unwanted words:

我使用了最常用的选项,并创建了一个函数,该函数将使用另一组不需要的单词来清除一组单词:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

To use, do the following:

使用方法如下:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)

#18


1  

Non-destructive removal:

非破坏性拆卸:

function removeArrayValue(array, value)
{
    var thisArray = array.slice(0); // copy the array so method is non-destructive

    var idx = thisArray.indexOf(value); // initialise idx

    while(idx != -1)
    {
        thisArray.splice(idx, 1); // chop out element at idx

        idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
    }

    return thisArray;
}

#19


1  

If you have unique values in your array, you can use Set, and it has delete:

如果你的数组中有唯一的值,你可以使用Set,它有delete:

var mySet = new Set(['foo']);
mySet.delete('foo'); // Returns true.  Successfully removed.
mySet.has('foo');    // Returns false. The "foo" element is no longer present.

#20


1  

function removeFrmArr(array, element) {
  return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(a, 3);
// return value like this
//[1, 2, 4, 5]

#21


1  

You can use without or pull from Lodash:

你可以不用或拉出Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]

#22


0  

var remove = function(array, value) {
    var index = null;

    while ((index = array.indexOf(value)) !== -1)
        array.splice(index, 1);

    return array;
};

#23


0  

I tried using the function method from jbaron above but found that I needed to keep the original array intact for use later, and creating a new array like this:

我尝试使用上面的jbaron的函数方法,但发现我需要保留原来的数组,以便以后使用,并创建这样的新数组:

var newArray = referenceArray;

apparently creates by reference instead of value because when I removed an element from newArray the referenceArray also had it removed. So I decided to create a new array each time like this:

显然是由引用而不是值创建的,因为当我从newArray中删除一个元素时,referenceArray也删除了它。所以我决定每次都创建一个新的数组:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

Then I use it like this in another function:

然后我在另一个函数中使用它:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

Now the vesselArr remains intact while each time I execute the above code the otherVessels array includes all but the latest vesselID element.

现在,vesselArr保持完整,而每次执行上面的代码时,其他容器阵列包括了最新的vesselID元素。

#24


0  

CoffeeScript+jQuery variant:

CoffeeScript + jQuery变体:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

it remove only one, not all.

它只除去一个,不是全部。

#25


0  

//This function allows remove even array from array
var removeFromArr = function(arr, elem) { 
    var i, len = arr.length, new_arr = [],
    sort_fn = function (a, b) { return a - b; };
    for (i = 0; i < len; i += 1) {
        if (typeof elem === 'object' && typeof arr[i] === 'object') {
            if (arr[i].toString() === elem.toString()) {
                continue;
            } else {                    
                if (arr[i].sort(sort_fn).toString() === elem.sort(sort_fn).toString()) {
                    continue;
                }
            }
        }
        if (arr[i] !== elem) {
            new_arr.push(arr[i]);
        }
    }
    return new_arr;
}

Example of using

使用的例子

var arr = [1, '2', [1 , 1] , 'abc', 1, '1', 1];
removeFromArr(arr, 1);
//["2", [1, 1], "abc", "1"]

var arr = [[1, 2] , 2, 'a', [2, 1], [1, 1, 2]];
removeFromArr(arr, [1,2]);
//[2, "a", [1, 1, 2]]

#26


0  

Another variation:

另一个变化:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

It's indexOf() inside a loop again, but on the assumption that the array to remove is small relative to the array to be cleaned; every removal shortens the while loop.

它是在一个循环内的indexOf(),但是假设要清除的数组相对于要清理的数组是小的;每次去除都会缩短while循环。

#27


0  

//edited thanks to MarcoCI for the advice

//感谢MarcoCI的建议。

try this:

试试这个:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

hope this help you

希望这有助于你

#28


0  

let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]

#29


-2  

var ary = ['three', 'seven', 'eleven'];
_.pull(ary, 'seven'); // ['three', 'eleven']
console.log(ary)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js"></script>