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.
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.
xxxxxxxxxx
1
const findUniqueItems = (array, comparer = (a, b) => a - b) => {
2
if (array.length === 0) {
3
return [];
4
}
5
const result = [];
6
const blocker = new Set(); // prevents against items duplication
7
for (const item of array) {
8
if (blocker.has(item)) {
9
continue;
10
}
11
blocker.add(item);
12
result.push(item);
13
}
14
return result.sort(comparer);
15
};
16
17
18
// Usage example:
19
20
const array = [2, 3, 1, 1, 1, 2, 2, 3, 3];
21
const uniqueItems = findUniqueItems(array);
22
23
console.log(JSON.stringify(uniqueItems)); // [1,2,3]
Note:
Sorting the array at the end (after removing duplicates) makes this solution more efficient.
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.
xxxxxxxxxx
1
const findUniqueItems = (array, comparer = (a, b) => a - b) => {
2
if (array.length === 0) {
3
return [];
4
}
5
const input = array.slice().sort(comparer);
6
const result = [];
7
for (let i = 1; i < input.length; ++i) {
8
const value = input[i - 1];
9
while (value === input[i]) {
10
i += 1;
11
}
12
result.push(value);
13
}
14
return result;
15
};
16
17
18
// Usage example:
19
20
const array = [2, 3, 1, 1, 1, 2, 2, 3, 3];
21
const uniqueItems = findUniqueItems(array);
22
23
console.log(JSON.stringify(uniqueItems)); // [1,2,3]