Get unique item from two different array in JavaScript


We are required to make a function that accepts an array of arrays, and returns a new array with all elements present in the original array of arrays but remove the duplicate items.

For example − If the input is −

const arr = [
   [12, 45, 65, 76, 76, 87, 98],
   [54, 65, 98, 23, 78, 9, 1, 3],
   [87, 98, 3, 2, 123, 877, 22, 5, 23, 67]
];

Then the output should be single array of unique elements like this −

[
   12, 45, 54, 78, 9,
   1, 2, 123, 877, 22,
   5, 67
]

Example

const arr = [
   [12, 45, 65, 76, 76, 87, 98],
   [54, 65, 98, 23, 78, 9, 1, 3],
   [87, 98, 3, 2, 123, 877, 22, 5, 23, 67]
];
const getUnique = (arr) => {
   const newArray = [];
   arr.forEach((el) => newArray.push(...el));
   return newArray.filter((item, index) => {
      return newArray.indexOf(item) === newArray.lastIndexOf(item);
   });
};
console.log(getUnique(arr));

Output

The output in the console will be −

[
   12, 45, 54, 78, 9,
   1, 2, 123, 877, 22,
   5, 67
]

Updated on: 21-Aug-2020

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements