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

array.remove(value);

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


当前回答

大部分答案都用...

循环的索引和组合删除过滤器

虽然所有解决方案都应该采用这些方法,但我想我们可以使用弦操纵。

需要注意的关于这一解决办法的要点 -- --

这将在数据中留下漏洞( 可以通过额外的过滤器将其移除 ) 此解决方案不仅适用于原始搜索值, 也适用于对象 。

诀窍是...

字符串字符串返回分隔符上的分解数据,以空字符串替换输入数据集中的搜索值。

    remove = (input, value) => {
        const stringVal = JSON.stringify(value);
        const result = JSON.stringify(input)

        return result.replace(stringVal, "").split(",");
    }

本文创建了一个测试对象和数字的 JSF 中心- https://jsfidle.net/4t7zhkce/33/

检查小提琴中的移除方法 。

其他回答

我刚刚通过对象.defineProperty在 Array. prototype 上创建了一个多填充器, 以便删除一个阵列中想要的元素, 而不会导致在... 的... 。

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

删除整数值

var a = [1, 2, 3]
a.remove(2)
a // Output => [1, 3]

删除字符串值

var a = ['a', 'ab', 'abc']
a.remove('abc')
a // Output => ['a', 'ab']

删除布尔值

var a = [true, false, true]
a.remove(false)
a // Output => [true, true]

也可以通过此 Array. prototype. remove 方法从数组中移除对象。您只需要指定要删除对象的键值 {% 。

删除对象值

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

组合法通过删除或替换现有元素和/或添加新元素来改变数组的内容。

数组。 spice( 开始 [, 删除 [, 删除 [, 项1 [, 项2 [, . ] ] ] ]

开始

开始更改数组的索引( 与源值为 0 ) 。 如果数组的长度大于数组的长度, 则实际起始指数将设置为数组的长度。 如果为负, 则开始从数组结尾处( 与源值为-1) 的许多元素, 如果绝对值大于数组的长度, 则将设置为 0 。

删除“ 计算” 选项@ action

表示要删除的旧数组元素数的整数。

如果删除“计算”被省略,或者如果其值大于数组。 长度 - 开始( 即如果它大于数组中剩下的元素数量, 从开始) , 那么从开始到数组结尾的所有元素都将删除。 如果删除“ 计算” 0 或“ 负” , 则不删除任何元素。 在这种情况下, 您应该至少指定一个新元素( 见下文) 。

第1项,第2项,...可选

要添加到数组的元素, 从起始索引开始。 如果您不指定任何元素, 组合() 只会从数组中删除元素 。

如需更多参考,请通过:

Array. prototype.spice ()

有许多方法可以从 JavaScript 阵列中去除一个特定元素。 下面是我研究中可以找到的五种最佳方法。

1. 直接使用“ splice () ” 方法

在以下代码段,从数组中删除特定预定位置的元素。

语法: 数组_ name.spice( begin_ index, 数字_ elements_ remove) ; 应用程序 :

var arr = [1、2、3、4、5、6、7、8、9、10]; 控制台.log ("原件阵列: "+arr " ; var remote = ar.spice(4、2); 控制台.log ("修改后的阵列: "+arr " ; 控制台.log ("元素删除: "+删除 " );

2. 使用“ splice() () ” 方法用“ valice () ” 方法用“ value () ” 删除元素

在以下代码段中,我们可以使用循环内的条件,删除所有等于预先确定值(前:所有元素等于值6)的所有元素。

var arr = [1, 2, 6, 3, 2, 6, 7, 8, 8, 9, 10] 控制台.log ("原件阵列: "+arr”; 对于 (var i = 0; i < arr. 长度; i++) { { {var remove = rr.spice(i, 1); i-; }} 控制台. log ("修改阵列: "+arr " ); / / 6 被移除控制台. log ("重新删除的元素: "+删除 ");

3. 使用“过滤器()”方法删除按值选择的元素

与使用“ spice() () ” 方法的执行类似, 但它没有改变现有的数组, 而是创造了新的元素阵列, 从而删除了不想要的元素 。

var 数组 = [1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10] ; var 过滤 = 数组. filter( 函数( 值, 索引, rr) { 返回值 = 6 ; } ; 控制台. log ("原件数组 : "+array" ); 控制台. log ("新建数组 : "+filtered" ; / 6 被删除

4. 在“ Lodash” JavaScript 库中使用“ remove () ” 方法

在下面的代码段中, JavaScript 库里有叫作“ Lodash ” 的删除() 方法。 这个方法也与过滤方法相似 。

var 数组 = [1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10] 控制台. log ("原件数组: "+数组: "+数组: "+ + + + 数组: "; var remote Eplement = _.remove (ary, 函数(n) { return n\\ 6; }) 控制台. log ("修改后的数组: "+ 数组: "+ 数组: "removed 元素: "+ removeElement 元素 " ); / / 6 被删除 < src=" https://cdn.jsdelivr.net/npm/lodash@4.17.21lodash.min.js" / stamp >

5. 制作自定义除去方法

JavaScript没有本地的“ array. remove” 方法, 但我们可以创建一种使用以上方法的方法, 用于在以下代码片段中执行 。

var 数组 = [1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10] ; 函数数组 remove( arve, value) { 返回 arr. filter( 函数( 元素) { 返回元素 $= = 值;} } 控制台. log (" 原件数组: "+ 数组 " ); 控制台. log (" 修改数组: "+ trightremove( 数组, 6) ); / / 6 被删除 。

最后方法(第5项)更适合解决上述问题。

删除单个元素

function removeSingle(array, element) {
    const index = array.indexOf(element)
    if (index >= 0) {
        array.splice(index, 1)
    }
}

删除多个元素, 位置内

这对于确保算法在O(N)时间运行更为复杂。

function removeAll(array, element) {
    let newLength = 0
    for (const elem of array) {
        if (elem !== number) {
            array[newLength++] = elem
        }
    }
    array.length = newLength
}

删除多个元素,创建新对象

array.filter(elem => elem !== number)

我张贴我的代码,删除一个阵列元素, 并缩短阵列长度 。

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