How to create a list of unique items in JavaScript?

后端 未结 8 414
半阙折子戏
半阙折子戏 2020-12-09 11:54

In my CouchDB reduce function I need to reduce a list of items to the unique ones.

Note: In that case it\'s ok to have a list, it will be a small number of items

相关标签:
8条回答
  • 2020-12-09 12:32

    An alternative that's suitable for small lists would be to ape the Unix command line approach of sort | uniq:

        function unique(a) {
            return a.sort().filter(function(value, index, array) {
                return (index === 0) || (value !== array[index-1]);
            });
        }
    

    This function sorts the argument, and then filters the result to omit any items that are equal to their predecessor.

    The keys-based approach is fine, and will have better performance characteristics for large numbers of items (O(n) for inserting n items into a hashtable, compared to O(n log n) for sorting the array). However, this is unlikely to be noticeable on small lists. Moreover, with this version you could modify it to use a different sorting or equality function if necessary; with hash keys you're stuck with JavaScripts notion of key equality.

    0 讨论(0)
  • 2020-12-09 12:34

    Commonly, the approach you used is a good idea. But I could propose a solution that will make the algorithm a lot faster.

    function unique(arr) {
        var u = {}, a = [];
        for(var i = 0, l = arr.length; i < l; ++i){
            if(!u.hasOwnProperty(arr[i])) {
                a.push(arr[i]);
                u[arr[i]] = 1;
            }
        }
        return a;
    }
    

    As you can see we have only one loop here.

    I've made an example that is testing both your and my solutions. Try to play with it.

    0 讨论(0)
提交回复
热议问题