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

array.remove(value);

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


当前回答

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

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

拼盘 () 方法

array.splice(index, 1);    

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

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

删除方法

delete array[index]

过滤 () 方法

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

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

Eleem 是您要从数组中删除的元素, 数组是您的数组名称 。

其他回答

您可以简单地将删除函数添加到数组原体Type

类似的东西 :

Array.prototype.remove = function(value) {
  return  this.filter(item => item !== value)
}

Array. prototype. remove = 函数( 值) { 返回此功能 。 filter (项目 项 ! === value) } 让阵列 = [10, 15,20] 结果 = 数组. remove(10) 控制台.log (结果) (结果)

如果你想删除几个项目, 我发现这是最容易的:

const oldArray = [1, 2, 3, 4, 5]
const removeItems = [1, 3, 5]

const newArray = oldArray.filter((value) => {
    return !removeItems.includes(value)
})

console.log(newArray)

产出:

[2, 4]

除了所有这些解决方案之外, 它也可以用阵列来完成. 减量...

const removeItem = 
    idx => 
    arr => 
    arr.reduce((acc, a, i) =>  idx === i ? acc : acc.concat(a), [])

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

...或者一个循环函数(诚实地说不是那么优雅...也许有人有更好的循环解决方案? ? )...

const removeItemPrep = 
    acc => 
    i => 
    idx => 
    arr => 

    // If the index equals i, just feed in the unchanged accumulator(acc) else...
    i === idx ? removeItemPrep(acc)(i + 1)(idx)(arr) :

    // If the array length + 1 of the accumulator is smaller than the array length of the original array concatenate the array element at index i else... 
    acc.length + 1 < arr.length ? removeItemPrep(acc.concat(arr[i]))(i + 1)(idx)(arr) : 

    // return the accumulator
    acc 

const removeItem = removeItemPrep([])(0)

const array = [1, 2, 3]
const index = 1

const newArray = removeItem(index)(array) 

console.log(newArray) // logs the following array to the console : [1, 3]

使用不同种类数组的过滤器

    **simple array**
    const arr = ['1','2','3'];
    const updatedArr = arr.filter(e => e !== '3');
    console.warn(updatedArr);

    **array of object**
    const newArr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}]
    const updatedNewArr = newArr.filter(e => e.id !== 3);
    console.warn(updatedNewArr);

    **array of object with different parameter name**
    const newArr = [{SINGLE_MDMC:{id:1,cout:10}},{BULK_MDMC:{id:1,cout:15}},{WPS_MDMC:{id:2,cout:10}},]
    const newArray = newArr.filter((item) => !Object.keys(item).includes('SINGLE_MDMC'));
    console.log(newArray)

删除上次的元素

arrName.pop();

删除第一个元素

arrName.shift();

从中间删除

arrName.splice(starting index, number of element you wnt to delete);

Example: arrName.splice(1, 1);

删除最后一个元素

arrName.splice(-1);

使用数组索引编号删除

 delete arrName[1];