将两个数组与对象进行比较,并显示删除了哪个项目

时间:2018-09-26 13:44:37

标签: javascript

我有两个数组要比较,并检查其中一个数组中是否有已删除的项目。如果有区别给我看(已删除的项目)

这是下面我想要实现的代码:

function compareFilters (a1, a2) {
     var a = [], diff = [];

     for (var i = 0; i < a1.length; i++) {
          a[a1[i]] = true;
     }

     for (var i = 0; i < a2.length; i++) {
        if (a[a2[i]]) {
          delete a[a2[i]];
        } else {
           a[a2[i]] = true;
        }
      }

      for (var k in a) {
        console.log('k', k);
        diff.push(k);
      }

      return diff;
}

console.log(filters);

console.log(filters, queryBuilderFilters, compareFilters(queryBuilderFilters, filters));

这将记录两个看起来像这样的数组:

[
 0: {
    id: "AggregatedFields.ReturnOnAdSpend", 
    label: "ROAS (Return on Ad Spend)", 
    type: "integer", 
    description: "The ROAS (Return on Ad Spend)."
},
1: {
    id: "AggregatedFields.ROIExcludingAssisted", 
    label: "ROI excl. assisted", 
    type: "integer", 
    description: "The ROI excluding any assisted values. 
}
]

compareFilters函数的输出为0: "[object Object]"

如何在此函数中返回对象的标签?

2 个答案:

答案 0 :(得分:2)

此示例说明了您想要的

var completedList = [1,2,3,4,7,8];
var invalidList = new Set([3,4,5,6]);
// filter the items from the invalid list, out of the complete list
var validList = completedList.filter((item) => {
  return !invalidList.has(item);
})
console.log(validList); // Print [1,2,7,8]

// get a Set of the distinct, valid items
var validItems = new Set(validList);

答案 1 :(得分:0)

您可以尝试此操作,假设每个数组中的对象具有相同的引用并且不是副本:

function compareFilters (a1, a2) {
    const a1l = a1.length;
    const a2l = a2.length;
    
    // Both arrays are considered to be equal
    if(a1l === a2l) return;
    
    let completed;
    let unCompleted;
    let deletedValue;

    if(a1l > a2l) {
        completed = a1;
        unCompleted = a2;
    } else {
        completed = a2;
        unCompleted = a1;
    }

    for(let i = 0; i < completed.lenth; i++) {
        if(completed[i] !== unCompleted[i]) {
            return completed[i].label;
        }
    }
}

如果两个数组具有相同数量的元素,它将返回undefined。否则,它将返回在一个数组中而不是另一个数组中的第一个元素的标签。