Open In App

JavaScript – Print Unique Elements From Two Unsorted Arrays

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the different approaches to print unique elements from two unsorted arrays using JavaScript

1. Using filter() method

We can filter all the unique elements using the filter() method. Then we will make one new array to concat our filtered array.

JavaScript
let a1 = [54, 71, 58, 95, 20];
let a2 = [71, 51, 54, 33, 80];

let uni1 = a1.filter((o) =>
    a2.indexOf(o) === -1);
let uni2 = a2.filter((o) =>
    a1.indexOf(o) === -1);

const res = uni1.concat(uni2);
console.log(res);

Output
[ 58, 95, 20, 51, 33, 80 ]

In this example,

  • uni1 filters elements in a1 that are not in a2.
  • uni2 filters elements in a2 that are not in a1.
  • concat combines the unique elements from both arrays.
  • Unique elements from a1 and a2.

2. Using Sets

To print unique elements from two unsorted arrays in JavaScript using Sets, combine the arrays into a Set, then convert the Set back into an array.

JavaScript
const a1 = [54, 71, 58, 95, 20];
const a2 = [71, 51, 54, 33, 80];

const set1 = new Set(a1);
const set2 = new Set(a2);

const uni1 = a1.filter(item => !set2.has(item));
const uni2 = a2.filter(item => !set1.has(item));

const res = [...uni1, ...uni2];
console.log(res); 

Output
[ 58, 95, 20, 51, 33, 80 ]

In this example

  • set1 and set2 store unique values of a1 and a2.
  • uni1 filters elements in a1 not in set2.
  • uni2 filters elements in a2 not in set1.
  • Combine uni1 and uni2 using the spread operator for unique elements.
  • Unique elements from both arrays.

3. Using a Frequency Map

A frequency map provides a structured way to count occurrences across both arrays.

JavaScript
const a1 = [54, 71, 58, 95, 20];
const a2 = [71, 51, 54, 33, 80];

const a = [...a1, ...a2];
const freq = a.reduce((acc, el) => {
    acc[el] = (acc[el] || 0) + 1;
    return acc;
}, {});

const elem = Object.keys(freq).filter(key => 
    freq[key] === 1).map(Number);

console.log(elem);

Output
[ 20, 33, 51, 58, 80, 95 ]

In this example

  • combine a1 and a2 into a.
  • Use reduce to create a frequency count of each element.
  • Filter keys with a frequency of 1 (unique elements) and convert them back to numbers.

4. Using External Libraries (Lodash)

Libraries like Lodash simplify tasks like finding unique elements.

JavaScript
const _ = require('lodash');

const uniqueElements = _.xor(arr1, arr2);
console.log(uniqueElements);


Next Article

Similar Reads