HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Remove duplicates in array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
removearrayduplicates

Problem

This function sorts an array and returns the unique items. I'm trying to get it down to a readable 5 lines of code. So far I've renamed the variable cursor variable and inlined the assignments.
I'll appreciate fresh eyes.

Before

function uniques(array) {
    var result = [], val, ridx;
    outer:
    for (var i = 0, length = array.length; i < length; i++) {
        val = array[i];
        ridx = result.length;
        while (ridx--) {
          if (val === result[ridx]) continue outer;
        }
        result.push(val);
    }
    return result;
}


After

function uniques(array) {
    var result = [], val, cursor;
    outer:
        for (var i = 0, length = array.length; i < length; i++) {
        val = array[i], cursor = result.length;
        while (cursor--) {
          if (val === result[cursor]) continue outer;
        }
        result.push(val);
    }
    return result;
}

Solution

This function sorts an array and returns the unique items

  • Remove duplicates from the array using Array#filter



  • Sort the array using Array#sort



Code:

function uniques(arr) {
    // Remove the duplicate elements from the array
    return arr.filter(function (element, index, arr) {
        return arr.indexOf(element) === index;
    }).sort(function (a, b) {
        return a - b;
    });
}

Code Snippets

function uniques(arr) {
    // Remove the duplicate elements from the array
    return arr.filter(function (element, index, arr) {
        return arr.indexOf(element) === index;
    }).sort(function (a, b) {
        return a - b;
    });
}

Context

StackExchange Code Review Q#111302, answer score: 3

Revisions (0)

No revisions yet.