How to create a list of unique items in JavaScript?

后端 未结 8 427
半阙折子戏
半阙折子戏 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.

提交回复
热议问题