Finding items that appear only one time in a Javascript array

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

    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;
    };
    
    var items = ['txfa2', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4', 'txfa8', 'txfa9', 'txfa2', 'txfa8'];
    
    console.log(singles( items ))

    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

    enter image description here

提交回复
热议问题