如何从满足条件的数组中删除元素

时间:2014-07-19 05:21:43

标签: javascript

我想删除满足条件的json元素。为此,我使用了给定的代码

var index = -1;
for (var i = 0; i < data.dashLayout.dashlets.length; i++) {
  if (data.dashLayout.dashlets[i].rowNo == selectedrowno) {
    if (index == -1 || data.dashLayout.dashlets[i].rowNo < data.dashLayout.dashlets[index].rowNo) {
      index = i;
    }
  }
if (index != -1) {
       data.dashLayout.dashlets.splice(index, 1);
    }
}

但迭代没有完成,因为data.dashLayout.dashlets.length正在通过拼接减少。我该如何解决这个问题?我想删除所有满足条件的项目。请帮忙

5 个答案:

答案 0 :(得分:1)

另外两个解决方案

var a = [2,5,8,13,9,1,4,8,10], l = a.length, c = 5;

// using reverse loop
while(l--){
    if(a[l] < c) a.splice(l, 1);
}

// using filter 
var b = a.filter(function(e, c) {
    return --e > c;
});

console.log(a); // [5, 8, 13, 9, 8, 10]  
console.log(b); // [5, 8, 13, 9, 8, 10]

答案 1 :(得分:0)

如果你在循环中拆分数组。数组将减少你不应该完全迭代,所以你必须思考不同的想法。所以我的解决方案是你必须存储基于你必须删除数组的索引。平均每次更改索引所以你必须使用-1

var index = -1;
var arr = []  // make array
for (var i = 0; i < data.dashLayout.dashlets.length; i++) {
    if (data.dashLayout.dashlets[i].rowNo == selectedrowno) {
        if (index == -1 || data.dashLayout.dashlets[i].rowNo < data.dashLayout.dashlets[index].rowNo) {
            index = i;
        }
    }
    if (index != -1) {
        // data.dashLayout.dashlets.splice(index, 1);

        arr.push(index);  //stored it
    }
}

// to remove 

for(var i in arr){
    if (i == 0) {
        data.dashLayout.dashlets.splice(arr[i], 1); // to remove init
    } else {
        data.dashLayout.dashlets.splice(arr[i] - 1, 1); // now index is changed now use -1
    }
}

答案 2 :(得分:0)

我建议使用Array对象的filter方法。 Filter方法将返回一个只包含所需元素的新数组。请参阅the definition of the filter method here

用法如下面的代码

var newDashlets = data.dashLayout.dashlets.filter(function(dashlet, i) {

    // Here your code returns true if you want to keep dashlet. 
    // Return false if you don't want it.

});

答案 3 :(得分:0)

在jquery中

data.dashLayout.dashlets = $.grep(data.dashLayout.dashlets, function (dashList, indexpos) {
    if (dashList.rowNo == selectedrowno) {
        if (dashList.rowNo < data.dashLayout.dashlets[index].rowNo || index == -1) {
            index = indexpos;
            return false;
        }
    }
});

答案 4 :(得分:0)

在jquery中使用map

data.dashLayout.dashlets = $.map(data.dashLayout.dashlets, function (dashList, indexpos) {
     if (dashList.rowNo == selectedrowno) {
         if (dashList.rowNo < data.dashLayout.dashlets[index].rowNo || index == -1) {
             index = indexpos;
         } else {
             return dashList;
         }
     }
 });