【问题标题】:Javascript - Remove value from array if it doesn't exist in anotherJavascript - 如果另一个值不存在,则从数组中删除值
【发布时间】:2016-10-11 12:58:31
【问题描述】:

我有两个数组:

//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: {
  //...
}

【问题讨论】:

  • 您要查找两个列表的交集吗?每个列表中的项目是否唯一?
  • 您能否发布listobjects 的样本。
  • @MartinGottweis 添加了示例。
  • @Joe 是的,它们是独一无二的——没有重复或虚假值。我想十字路口是我要找的!

标签: javascript arrays loops


【解决方案1】:

您可以使用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);
&lt;script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    首先,您必须以某种方式对齐数据。我建议你去掉这些项目的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 框架来使您的项目可维护。这样您就可以只跟踪一个元素列表并让 angular 计算出重新渲染。

    【讨论】:

    • 谢谢马丁。我使用您的示例对其进行了整理。我已经将两个数据都存储在一个数组中,所以不需要重新映射它们:)
    • 乐于助人。祝你的项目好运。
    【解决方案3】:

    还有在过滤器中查找:

    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 ]
    

    【讨论】:

      【解决方案4】:

      如果 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 就是你想要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多