Languages
[Edit]
EN

JavaScript - sort array and get unique values

3 points
Created by:
Walter
586

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]

 

See also

  1. JavaScript - remove duplicates from array

References

  1. Set() constructor - JavaScript | MDN
  2. Set.prototype.has() - JavaScript | MDN
  3. Object.prototype.hasOwnProperty() - JavaScript | MDN

Alternative titles

  1. JavaScript - get sorted unique values from array
  2. JavaScript - sort array and remove duplicate elements
  3. JavaScript - sort array and remove duplicates
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join