Finding items that appear only one time in a Javascript array

前端 未结 5 1008
无人及你
无人及你 2021-01-14 09:45

I\'m trying to find the items that appear only one time in a Javascript array. In the following array:

[\'txfa2\',\'txfa9\',\'txfa2\',\'txfa1\',\'txfa3\',\'t         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 10:39

    /** 
     * Array.uniq();
     *
     * @author: Alexander Guiness
     * @param: {Array}
     * @return: {Array} An array of unique values
     * @licence: MIT
     * @use: Array.uniq([1,1,1,1,2,2,2,4,5,5,4]); //1,2,4,5
     * @date: Mon Jul 26 10:00:00 2011
    */
    
    (function($) {
        'use strict';
        if(!$.uniq) {
            $.uniq = function(array) {
                if(Object.prototype.toString.call(array) !== '[object Array]')
                     return -1; 
    
                var i = array.length;
                array.sort();
    
                while(i--) {
                    if(array[i] == array[i-1]) {
                        array.splice(i, 1);
                    }
                }
                return array;
           }
    
        }
    }(Array));
    

    see the example

    or use: jQuery.unique([]);

提交回复
热议问题