How to use filter() method In Javascript
We can filter all the element which is unique by using the filter() method. Then we will make one new array in which we concat our filtered array.
Example:
let arr1 = [54, 71, 58, 95, 20];
let arr2 = [71, 51, 54, 33, 80];
let unique1 = arr1.filter((o) =>
arr2.indexOf(o) === -1);
let unique2 = arr2.filter((o) =>
arr1.indexOf(o) === -1);
const unique = unique1.concat(unique2);
console.log(unique);
Output
[ 58, 95, 20, 51, 33, 80 ]
How to print unique elements from two unsorted arrays using JavaScript ?
Given two unsorted arrays, the task is to write a JavaScript program to print the unique (uncommon) elements in the two arrays.
These are the way by which we print unique elements from two unsorted arrays using JavaScript:
Table of Content
- Using for loop
- Using filter() method
- Using Sets