javascript - 如何删除重复项并计算两个数组之间的差异?

标签 javascript ecmascript-6

我可以在嵌套映射中获取相同值的值。但如何获得两者之间的差异呢?

我尝试了 map 、过滤器,但我不知道如何正确删除重复值。

const responseData = [
  { value: "red", label: "Red" },
  { value: "blue", label: "Blue" }
];
const fixedColors = [
  { value: "red", label: "Red" },
  { value: "blue", label: "Blue" },
  { value: "yellow", label: "Yellow" },
  { value: "orange", label: "Orange" }
];

responseData.map(opt => {
  fixedColors.findIndex(obj => {
    if (obj.value === opt.value) {
      testArray.push(opt);
    } else {
      testArray2.push(obj);
    }
  });
});

我可以在两个数组上获得相同的值,但我无法得到差异。我不知道如何使用 ES6 正确执行它。

最佳答案

过滤您的响应,仅包含尚未包含在fixedColors中的值,并将结果与​​fixedColorsconcat

const responseData = [{value: "purple", label:"Purple is new"}, {value: "blue", label:"Blue"}]

const fixedColors = [{value: "red", label:"Red"}, {value: "blue", label:"Blue"},{value: "yellow", label:"Yellow"}, {value: "orange", label:"Orange"}]

const existingValues = fixedColors.map(x => x.value)
const valuesToAdd = responseData.filter(x => !existingValues.includes(x.value))

const newValues = fixedColors.concat(valuesToAdd)

console.log(newValues)

关于javascript - 如何删除重复项并计算两个数组之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397164/

相关文章:

javascript - setState react 生成数组结果

javascript - 如何让 jquery 选择器在更改处理程序中看到更新的 dom

javascript - 如何结合 .each 与 .not()

javascript - 在 KineticJS 中绘制圆弧

javascript - 如何在react-native中动态加载模块?

javascript - 为什么你不应该在 ES6 中使用 import all

javascript - 带有自定义包路径的 dojo 1.9 配置

javascript - ASP.NET MVC AJAX 将参数传递给 Controller

javascript - 解构对象数组 (es6)

javascript - 使用空元素迭代 Array (ES6)