0

I can get the values of same values inside a nested map. But how to get the difference between the two?

I tried map, filter but I can't get the hang of how to do it properly for removing the duplicate values.

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);
    }
  });
});

I can get the same values on both arrays, I can't get the difference. I don't get how to properly execute it using ES6.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
drini
  • 25
  • 4
  • 1
    Possible duplicate of [How to get the difference between two arrays in JavaScript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – Emile Bergeron Oct 15 '19 at 14:50

1 Answers1

1

filter your response to include only the values not already included in fixedColors and concat the result with fixedColors

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)
Dupocas
  • 20,285
  • 6
  • 38
  • 56