Finding items that appear only one time in a Javascript array

前端 未结 5 957
无人及你
无人及你 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:43

    By "find the unique items" I believe you mean "find items that are not repeated" (as compared to "find distinct values")? Also, I don't understand why your haspair variable is a string: your sample data has more than one pair in it. Anyway...

    There are lots of ways to do this, but I'd use an object to make a count for each distinct values. That makes it easy to generate an array of the non-repeated items and an array of the repeated items, and an array of the distinct values. Obviously if you don't need all three you omit the ones you don't care about, but I've shown all three below which is why it may look a bit longer than you wanted. Of course if you want a count of how many are in any category you just use the array length.

    var items = ['txfa2', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4', 'txfa8', 'txfa9', 'txfa2', 'txfa8'];
    
    var working = {},
        hasPairs = [],
        noPairs = [],
        distinct = [],
        i, k;
    
    for (i=0; i < items.length; i++)
       if (working.hasOwnProperty(items[i]))
          working[items[i]]++;
       else
          working[items[i]] = 1;
    
    for (k in working) {
       if (working[k] > 1)
          hasPairs.push(k);
       else
          noPairs.push(k);
       distinct.push(k);
    }
    

    Note: I've written the above with plain JavaScript, without using newer array functions that might not be supported by older browsers. Obviously you can take the basic algorithm and use jQuery to iterate through the initial array and/or the properties of working, or you can use .forEach() if you don't care about IE < 9, etc.

提交回复
热议问题