Javascript 按值从数组中删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8873601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:52:19  来源:igfitidea点击:

Remove an item from an array by value

javascriptjqueryarrayseach

提问by Alex Guerin

I have an array of items like:

我有一系列项目,例如:

var items = [id: "animal", type: "cat", cute: "yes"]

And I'm trying to remove any items that match the ID given. In this case; animal

我正在尝试删除与给定 ID 匹配的所有项目。在这种情况下;animal

I'm stuck! I can get it to work easily by having a more simpler array but this is not what I need... I also need to remove the item by value as I don't want the hassle of referring to items by their index.

我被卡住了!通过使用更简单的数组,我可以让它轻松工作,但这不是我需要的......我还需要按值删除项目,因为我不希望通过索引引用项目的麻烦。

Is there a jQuery method I could use where I don't need to iterate through the items array, rather specify a selector?

有没有我可以使用的 jQuery 方法,我不需要遍历 items 数组,而是指定一个选择器?

Here is my jsFiddle: http://jsfiddle.net/zafrX/

这是我的 jsFiddle:http: //jsfiddle.net/zafrX/

回答by Adam Rackis

I'm not sure how much of a hassle it is to refer to array items by index. The standard way to remove array items is with the splice method

我不确定按索引引用数组项有多少麻烦。删除数组项的标准方法是使用splice 方法

for (var i = 0; i < items.length; i++)
    if (items[i] === "animal") { 
        items.splice(i, 1);
        break;
    }

And of course you can generalize this into a helper function so you don't have to duplicate this everywhere.

当然,您可以将其概括为辅助函数,这样您就不必在任何地方复制它。



EDIT

编辑

I just noticed this incorrect syntax:

我刚刚注意到这个不正确的语法:

var items = [id: "animal", type: "cat", cute: "yes"]

Did you want something like this:

你想要这样的东西:

 var items = [ {id: "animal",  type: "cat", cute: "yes"}, {id: "mouse",  type: "rodent", cute: "no"}];

That would change the removal code to this:

这会将删除代码更改为:

for (var i = 0; i < items.length; i++)
    if (items[i].id && items[i].id === "animal") { 
        items.splice(i, 1);
        break;
    }

回答by Chtiwi Malek

No need for jQuery or any third party lib for this, now we can use the new ES5 filter :

不需要 jQuery 或任何第三方库,现在我们可以使用新的 ES5 过滤器:

let myArray = [{ id : 'a1', name : 'Rabbit'}, { id : 'a2', name : 'Cat'}];
myArray = myArray.filter(i => i.id !== 'a1');

回答by Milad Naseri

You can either use spliceor run a delete yourself. Here's an example:

您可以splice自己使用或运行删除。下面是一个例子:

for (var i = 0; i < items.length; i ++) {
    if (items[i] == "animal") { 
        items.splice(i, 1);
        break;
    }
}

回答by Playnox

There's a simple way!

有一个简单的方法!

myItems.splice(myItems.indexOf(myItems.find(row => row.id == id)), 1);

Demo below:

演示如下:

// define function
function delete_by_id(id) {

  var myItems = [{
    id: 1,
    type: "cat",
    cute: "yes"
  }, {
    id: 2,
    type: "rat",
    cute: "yes"
  }, {
    id: 3,
    type: "mouse",
    cute: "yes"
  }];

  // before
  console.log(myItems);

  myItems.splice(myItems.indexOf(myItems.find(item => item.id == id)), 1);

  // after 
  console.log(myItems);

}

// call function
delete_by_id(1);

回答by Aleksandar Vucetic

You should do it like this (make sure that you have the right syntax...you cannot have array with properties, but object inside {}and then you can iterate by keys and delete unwanted key):

你应该这样做(确保你有正确的语法......你不能有带有属性的数组,但里面有对象{},然后你可以通过键进行迭代并删除不需要的键):

var items = {id: "animal", type: "cat", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...

for(var p in items){
    if(items[p] === removeItem)
        delete items[p]
}

And to answer you question, you cannot apply jquery selectors to javascript objects. The best you can do to avoid forloop is to use $.each(which is a loop written in a more "functional" way).

为了回答您的问题,您不能将 jquery 选择器应用于 javascript 对象。避免for循环的最佳方法是使用$.each(这是一个以更“功能”的方式编写的循环)。

回答by Jeremy D

By using object notation : http://jsfiddle.net/jrm2k6/zafrX/2/

通过使用对象表示法:http: //jsfiddle.net/jrm2k6/zafrX/2/

var animal1 = {id: "animal", type: "cat", cute: "yes"}
var car2 = {id: "car", type: "pick-up", cute: "no"}
var animal3 = {id: "animal", type: "dog", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...

var array_items = []
array_items.push(animal1);
array_items.push(car2);
array_items.push(animal3);

for(var i=0;i<array_items.length;i++){
    if(array_items[i].id == removeItem){
        array_items.splice(i,1);
    }
}

//alert(array_items.length);  

回答by M?hre

Wow, so many ideas but still not what I wanted xD

哇,这么多想法,但仍然不是我想要的 xD

This will remove ALL entries of the given value and return the removed value:

这将删除给定值的所有条目并返回删除的值:

function removeOfArray(val, arr){
    var idx;
    var ret;
    while ((idx = arr.indexOf(val)) > -1){
        arr.splice(idx, 1);
        ret = val;
    }
    return ret;
}

Also I found other solutions here: Remove item from array by value

我还在这里找到了其他解决方案: 按值从数组中删除项目

回答by R Maharajan

-parray : list of array of object
-pstring :value to remove from the array
-ptag :using which tag we

function removeFromArr (parray,ptag,pstring){
 var b =[];
var count = 0;
for (var i =0;i<parray.length;i++){
 if(pstring != parray[i][ptag]){
 b[count] = parray[i];
 count++;
 }
}
 return b;
}

var lobj = [ {
 "SCHEME_CODE": "MIP65",
 "YEARS": "1",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.80",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.79"
 },
 {
 "SCHEME_CODE": "MIP65",
 "YEARS": "2",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.98",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.96"
 },
 {
 "SCHEME_CODE": "MIP65",
 "YEARS": "3",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "2.05",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "2.03"
 },
 {
 "SCHEME_CODE": "MIP65",
 "YEARS": "5",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "2.26",
 "FREQUENCY": "Monthly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "2.24"
 },
 {
 "SCHEME_CODE": "QIP65",
 "YEARS": "1",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.80",
 "FREQUENCY": "Quarterly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.79"
 },
 {
 "SCHEME_CODE": "QIP65",
 "YEARS": "2",
 "CURRENCY": "GBP",
 "MAX_AMT": 200000,
 "MIN_AMT": 1000,
 "AER_IR": "1.98",
 "FREQUENCY": "Quarterly",
 "CUST_TYPE": "RETAIL",
 "GROSS_IR": "1.97"
 },
]

function myFunction(){
 var final = removeFromArr(lobj,"SCHEME_CODE","MIP65");
 console.log(final);
}
<html>
<button onclick="myFunction()">Click me</button>
</html>

are going to remove from the objects

将从对象中删除

function removeFromArr(parray, pstring, ptag) {
        var farr = [];
        var count = 0;
        for (var i = 0; i < pa.length; i++) {
            if (pstring != pa[i][ptag]) {
                farr[count] = pa[i];
                count++;
            }
        }
        return farr;
    }