-2

Am trying the following

Input:
myarray1=['Tag A','Tag B','Tag C']
myarray2=['Tag B','Tag C']
myarray3=['Tag A','Tag D']

Output:

outputArray=['Tag A','Tag B','Tag C','Tag D']

The output array should conatin the unique values from the input arrays.

Am trying this in typescript but not able to find the unique values from input array. Any suggestions how to achieve this in optimal way

RBG
  • 91
  • 9
  • Use concat to create one array and then filter – George Dec 20 '18 at 15:47
  • In that question duplicates were removed from single array, here the question is from multiple arrays – RBG Dec 20 '18 at 16:42
  • Possible duplicate of [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) and [Getting a union of two arrays in JavaScript](https://stackoverflow.com/questions/3629817) – adiga Dec 20 '18 at 16:47
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Dec 20 '18 at 16:50

4 Answers4

3

Pass the merged arrays into a Set and spread that set into results array

myarray1=['Tag A','Tag B','Tag C']
myarray2=['Tag B','Tag C']
myarray3=['Tag A','Tag D']

const uniques = [...new Set(myarray1.concat(myarray2,myarray3))]

console.log(uniques)
charlietfl
  • 170,828
  • 13
  • 121
  • 150
2

You can easily do it with ES6 Spread and Set

myarray1=['Tag A','Tag B','Tag C']
myarray2=['Tag B','Tag C']
myarray3=['Tag A','Tag D']
const uniqueArr = [...new Set([...myarray1,...myarray1,...myarray3])];
console.log(uniqueArr)
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
1

Very simple, only using array functions, first you conctainate all of the arrays, then you use the fitler function to simply ensure that there's only ever unique values.

const myarray1 = ['Tag A', 'Tag B', 'Tag C'],
  myarray2 = ['Tag B', 'Tag C'],
  myarray3 = ['Tag A', 'Tag D'];

const mergedArray = Array.concat(myarray1, myarray2, myarray3).filter((s, i, array) => array.indexOf(s) === i);
console.log(mergedArray);
1

You can do it with reduce Set and spread operator.

let arr1=['Tag A','Tag B','Tag C']
let arr2=['Tag B','Tag C']
let arr3=['Tag A','Tag D']

let arr = [arr1,arr2,arr3]
let op = [...new Set( arr.reduce((o,c)=>o.concat(c),[]))];

console.log(op);
Code Maniac
  • 37,143
  • 5
  • 39
  • 60