Javascript - 如果数组中的值不存在,则从数组中删除值

时间:2016-10-11 12:58:31

标签: javascript arrays loops

我有两个数组:

//list elements from html
var list = document.querySelectorAll('#pres-list-ul li');
//list of retrieved objects from api
var objects = self.retrievedItems;

为了提高效率,列表的内容保存在html文件中(除非你刷新,否则不需要重新渲染相同的数据)

如果在检索到的对象中不再存在列表项,我想从html中删除它。

我知道它在下面代码的某处,但我无法解决。

//I need to compare the id? For that another loop - which will run hundreds and thousands of time?
for(var j = 0; j < objects.length; j++) {
  if(objects.indexOf(list[i]) === -1) {
    //false
  } else {
    //true
  }
}

情景:

list:  57 //local
objects:  56 //online

在列表中找到额外的值并将其删除。

列表:

<li id="item-5756" data-category="" data-group="" data-created="" data-author=""></li>

对象:

0: {
  id: //
  title: //
  description //
  // ...
}

1: {
  //...
}

4 个答案:

答案 0 :(得分:2)

您可以使用filter并检查数组是否匹配:

var array1 = [1,2,3,4,5,6,7,8,9],
    array2 = [1,2,3,4,5,6,7,8,9,10],
    result = [];

result = array2.filter(function(item){
  if ( array1.indexOf(item) !== -1 ) return item;
});

console.log(result);

在您的情况下,要比较数组中的对象,可以使用Lodash,例如:

var array1 = [{'id': 1,'title': 'Test','description': 'Test'}, {'id': 2,'title': 'Test','description': 'Test'}, {'id': 3,'title': 'Test','description': 'Test'}],
    array2 = [{'id': 1,'title': 'Test','description': 'Test'}, {'id': 12,'title': 'Test','description': 'Test'}, {'id': 3,'title': 'Test','description': 'Test'}],
    result = [];

array2.forEach(function(item1){
  array1.forEach(item2 =>{     
    if ( _.isEqual(item1, item2) ){
      result.push(item2);  
    }
  });
});

console.log(result);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

答案 1 :(得分:1)

首先,您必须以某种方式对齐数据。我建议你摆脱id="item-5756"的项目。请改用data-id="5756"。获得本地和远程ID的列表后,您可以使用indexOf执行建议,并隐藏不在远程的本地元素。

请在此处查看:https://jsfiddle.net/jrwyopvs/

var remote_data = {
    5756: {
        id: 5756,
        title: '',
        description: '',
    },
    5757: {
        id: 5757,
        title: '',
        description: '',
    },
    5758: {
        id: 5758,
        title: '',
        description: '',
    },
}

$(document).on('click', '.filter', filter_local)

function filter_local () {
    var local_ids = $('#pres-list-ul li').toArray().map(function (element) { return $(element).data('id') })
    var remote_ids = []
    for (remote_index in remote_data) {
        remote_ids.push(remote_data[remote_index].id)
    }
    console.log(local_ids, remote_ids)

    for (local_id in local_ids) {
        if (remote_ids.indexOf(local_ids[local_id]) == -1) {
            $('#pres-list-ul li[data-id="' + local_ids[local_id] + '"]').hide()
        }
    }
}

请注意,有几种改进方法:

更好的过滤算法:我建议的效率非常差。可以一次性对ID进行排序和过滤。使用[data="5678"]的查找速度也相当慢。

使用数据绑定:考虑使用angular或其他一些mvc框架来使您的项目可维护。通过这种方式,您可以跟踪一个元素列表,并让角度计算出重新渲染。

答案 2 :(得分:0)

还可以在过滤器内找到:

var list = [1,2,3,4,5,6,7,8,9];
var objects = [1,2,5,6,9,10,11,12,13,14];
var result = list.filter(item => objects.find(element => element === item));
console.log(result); //[ 1, 2, 5, 6, 9 ]

答案 3 :(得分:0)

如果BaseArray是arr1并且从服务器接收是arr2,则必须在arr1上执行循环,如果在arr2中找不到,则不要推送到arrOut。

var arr1=["abc","cde","efg","xyz"];
var arr2=["abc","cde","efg"];
var arrOut=[];
for(var i=0;i<arr1.length;i++){
    var out=arr2.find(function(element, index, array){return element===arr1[i];});
    if(out!=undefined){
        arrOut.push(out);
    }
}

然后arrOut就是你想要的。

相关问题