How to remove item from array by value?

2018-12-31 05:40发布

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

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.

30条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 05:47

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)
查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 05:50

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"]

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 05:52

You can use without or pull from Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
查看更多
墨雨无痕
5楼-- · 2018-12-31 05:53

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

For example, with this:

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

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

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

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

It reduces the code that you write.

查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 05:53

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

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}
查看更多
若你有天会懂
7楼-- · 2018-12-31 05:54

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;
}
查看更多
登录 后发表回答