javascript - 比较两个列表以查找新元素、删除的元素和现有元素

标签 javascript

我有两个这样的字符串列表:

let previous_id = ["5b7b5498ab3f510e307e7d04", "5b7ae97cc6d75e1331e28d9c", "5b7a0c207fab2722a2081caf"];
let current_id = ["5b7b5498ab3f510e307e7d04", "5b83e3b4412f370bd7b9a05d"];

我想比较两个列表的所有元素,以便知道哪一个仍在列表中,哪一个是新的,哪一个已被删除。

结果将是:

delete_id = ["5b7ae97cc6d75e1331e28d9c", "5b7a0c207fab2722a2081caf"];
new_id = ["5b83e3b4412f370bd7b9a05d"];
existing_id = ["5b7b5498ab3f510e307e7d04"];

有什么功能可以做到这一点吗?

我想避免使用多个 if 条件执行两个循环,如下所示:

let previous_id = ["5b7b5498ab3f510e307e7d04", "5b7ae97cc6d75e1331e28d9c", "5b7a0c207fab2722a2081caf"];
let current_id = ["5b7b5498ab3f510e307e7d04", "5b83e3b4412f370bd7b9a05d"];

delete_id = [];
new_id = [];
existing_id = [];

for(let item of previous_id){
   let index = current_id.indexOf(item);
   if(index == -1){
       delete_id.push(item);
   } else {
       existing_id.push(item);
   }
}

for(let item of current_id){
   let index = previous_id.indexOf(item);
   if(index == -1){
      new_id.push(item);
   }
}


console.log(delete_id)
console.log(new_id)
console.log(existing_id)

最佳答案

我会在集合操作之上构建您的数组操作。由于不应存在重复项,因此这是内部计算的正确结构。我不知道为什么 Set.prototype 至少没有 unionintersectiondifference ,但是自己编写它们非常简单。

// Set operations

const intersection = (set1, set2) => new Set([...set1].filter(x => set2.has(x)))
const difference = (set1, set2) => new Set([...set1].filter(x => !set2.has(x)))


// Array operations, builtt using the set ones
// NB: Arrays are NOT Sets, and there is some information lost in the conversion.
// But Sets are the proper data structure for unordered collections of unique values.

const intersectionA = (arr1, arr2) =>  Array.from(intersection(new Set(arr1), new Set(arr2)))
const differenceA = (arr1, arr2) => Array.from(difference(new Set(arr1), new Set(arr2)))


// Main code

const breakdown = (prev, curr) => ({
  delete_id: differenceA(prev, curr),
  new_id: differenceA(curr, prev),
  existing_id: intersectionA(prev, curr)
})

let previous_id = ["5b7b5498ab3f510e307e7d04", "5b7ae97cc6d75e1331e28d9c", "5b7a0c207fab2722a2081caf"];
let current_id = ["5b7b5498ab3f510e307e7d04", "5b83e3b4412f370bd7b9a05d"];

console.log(breakdown(previous_id, current_id))

如果您对多个循环的反对与代码膨胀有关,那么这可能会有所帮助。如果您认为多个循环是应用程序中的性能瓶颈(您已经对此进行了测试,对吧?),那么这根本没有帮助,因为它会针对您想要的每个输出单独循环,并且在数组之间的转换上还有额外的工作和集。但如果这些导致应用程序出现严重瓶颈,我会感到非常惊讶。

关于javascript - 比较两个列表以查找新元素、删除的元素和现有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52082003/

相关文章:

javascript - node.js 事件队列在哪里?

javascript - React 将数组从父状态传递到子状态

javascript - 在 HTML 中加载/调用 javascript 的适当位置

javascript - jquery get 语法与 php 和 mysql 进行输入验证

用于查找匹配属性值的 JavaScript for 循环在第一个对象之后停止迭代

javascript - 使用 jQuery 返回隐藏的 <td> 值

javascript - 问题 js Body.set 不更新对象位置

javascript - Nodejs 引用 module.exports

javascript - Jquery Live Load - 通过 ajax 加载表单

c# - SignalR 2.0.0.0 : $. 连接未定义