如何从数组中删除一个特定值? 类似 :

array.remove(value);

我必须使用核心核心核心JavaScript。 不允许框架 。


当前回答

您只需要按元素或索引过滤 :

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);

其他回答

要从数组中删除元素, 要从数组中除去元素, 组合、 过滤和删除

每个阵列都有自己的索引,它有助于用索引删除一个特定元素。

拼盘 () 方法

array.splice(index, 1);    

第一个参数是指数指数指数指数第二个是要从该索引中删除的元素数量。

因此,单一个元素,我们用1。

删除方法

delete array[index]

过滤 () 方法

如果您想要删除一个在数组中重复的元素, 那么过滤数组 :

removeAll = array.filter(e => e != elem);

何处处elem是要从数组中删除的元素。array您的数组名称。

您可以使用ES6. 例如,在此情况下删除值“ 3” :

var array=['1','2','3','4','5','6']
var newArray = array.filter((value)=>value!='3');
console.log(newArray);

产出:

["1", "2", "4", "5", "6"]

根据索引删除

函数返回在索引中没有元素的数组副本 :

/**
* 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 ]

以值删除

函数返回没有值的数组副本。

/**
* 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]

这提供了一个前提值, 而不是一个值 。

注:这将更新给定的数组, 并返回受影响的行 。

用法

var removed = helper.remove(arr, row => row.id === 5 );

var removed = helper.removeAll(arr, row => row.name.startsWith('BMW'));

定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义的定义定义定义定义定义定义的定义

var helper = {
 // Remove and return the first occurrence

 remove: 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

 removeAll: 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;
 },
};

我对基底 JavaScript 阵列进行了相当高效的扩展:

Array.prototype.drop = function(k) {
  var valueIndex = this.indexOf(k);
  while(valueIndex > -1) {
    this.removeAt(valueIndex);
    valueIndex = this.indexOf(k);
  }
};