EN
JavaScript - sort array and get unique values
3
points
In this article, we would like to show you how to sort an array and get unique values from it using JavaScript.
1. Set based approach
In this example, we create Set to be a blocker that helps us to remove duplicate items and return only unique ones. After that, we use sort() method to sort an array.
// ONLINE-RUNNER:browser;
const findUniqueItems = (array, comparer = (a, b) => a - b) => {
if (array.length === 0) {
return [];
}
const result = [];
const blocker = new Set(); // prevents against items duplication
for (const item of array) {
if (blocker.has(item)) {
continue;
}
blocker.add(item);
result.push(item);
}
return result.sort(comparer);
};
// Usage example:
const array = [2, 3, 1, 1, 1, 2, 2, 3, 3];
const uniqueItems = findUniqueItems(array);
console.log(JSON.stringify(uniqueItems)); // [1,2,3]
Note:
Sorting the array at the end (after removing duplicates) makes this solution more efficient.
2. Simple types approach
In this example, we firstly create a copy of an array using slice() method, then we sort it. After that, we loop through the sorted array and remove duplicate elements by pushing only unique items to the result array.
// ONLINE-RUNNER:browser;
const findUniqueItems = (array, comparer = (a, b) => a - b) => {
if (array.length === 0) {
return [];
}
const input = array.slice().sort(comparer);
const result = [];
for (let i = 1; i < input.length; ++i) {
const value = input[i - 1];
while (value === input[i]) {
i += 1;
}
result.push(value);
}
return result;
};
// Usage example:
const array = [2, 3, 1, 1, 1, 2, 2, 3, 3];
const uniqueItems = findUniqueItems(array);
console.log(JSON.stringify(uniqueItems)); // [1,2,3]