-1
let array1 = ["apple", "banana", "mango"];
let array2 = ["apple", "banana", "mango", "red", "green"];

I want output is = array3 = [ "red", "green"];

I want to concat array1 and array2 and remove the duplicate code and output is array3.

There are two common ways (in ES5 and ES6, respectively) of getting unique values in JavaScript arrays of primitive values. Basically, in ES5, you first define a distinct callback to check if a value first occurs in the original array, then filter the original array so that only first-occurred elements are kept.

akinuri
  • 10,690
  • 10
  • 65
  • 102

1 Answers1

0

You can easily filter out the common elements using Map as:

let array1 = ["apple", "banana", "mango"];
let array2 = ["apple", "banana", "mango", "red", "green"];

const map = [...array1, ...array2].reduce(
  (map, curr) => map.set(curr, (map.get(curr) ?? 0) + 1),
  new Map()
);

const result = [];
for (let [k, v] of map) {
  if (v === 1) result.push(k);
}
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • 1
    `I want to concat array1 and array2 and remove the duplicate code and output is array3.` Will this capture unique items in array1? – Mark Nov 20 '21 at 06:55
  • No It won't capture, because unique values are stored in `Set` not in `array1` or `array2` – DecPK Nov 20 '21 at 06:59
  • What I mean is what if array1 is `["apple", "banana", "mango", "orange"]` and array2 is the same. What is the expected result? – Mark Nov 20 '21 at 07:00
  • @Mark Answer edited... – DecPK Nov 20 '21 at 07:09