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 06:07

ES6 way.

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
查看更多
初与友歌
3楼-- · 2018-12-31 06:07

CoffeeScript+jQuery variant:

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.

查看更多
公子世无双
4楼-- · 2018-12-31 06:10

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.

What it does (from the doc link)

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.

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.

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

查看更多
孤独寂梦人
5楼-- · 2018-12-31 06:10
var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}
查看更多
一个人的天荒地老
6楼-- · 2018-12-31 06:10

What you're after is 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://stackoverflow.com/a/20827100/293492

查看更多
人气声优
7楼-- · 2018-12-31 06:12

You can do it with these two ways:

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

first:

arr.indexOf('3') !== -1 && arr.splice(arr.indexOf('3'), 1)

second (ES6):

arr = arr.filter(e => e !== '3')
查看更多
登录 后发表回答