Finding items that appear only once in a JavaScript array

advertisements

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','txfa4','txfa8','txfa9','txfa2','txfa8']

The result should be:

['txfa1','txfa3','txfa4']

I'm currently using the .each() function in jQuery and .sort(). Is there a smarter or better way on doing this? Do you know of any jQuery plugin that can do this in fewer lines of code.

<script src="../../js/jq.js"></script>
<script>
var items = ['txfa2', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4', 'txfa8', 'txfa9', 'txfa2', 'txfa8'];
var nopairs = []; //should contain only txfa1, txfa3, txfa4
var haspair = '';//contains the item which has pairs
var haspair_ctr = 0;
var nopair_ctr = 0;

var arranged = items.sort();

$(arranged).each(function(index){
    if(index != arranged.length){
        if(arranged[index] != arranged[index + 1] && arranged[index] != haspair){
            nopairs[nopair_ctr] = arranged[index];
            nopair_ctr++;

        }else{
            haspair  = arranged[index];

        }
    }

});
console.log(nopairs);

</script>


A concise way to do it:

function singles( array ) {
    for( var index = 0, single = []; index < array.length; index++ ) {
        if( array.indexOf( array[index], array.indexOf( array[index] ) + 1 ) == -1 ) single.push( array[index] );
    };
    return single;
};

Demo: http://jsfiddle.net/ThinkingStiff/C849F/

Here's the performance of the non-duplicate answers to this question (that actually work) showing this method (blue) is comparable with the other methods.

Performance: http://jsperf.com/find-array-singles/3