Finding items that appear only one time in a Javascript array

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

    Here's an example using ES5's functional methods, based on using an object to count the number of times each value occurs:

    function uniq(a) {
      // create a map from value -> count(value)
      var counts = a.reduce(function(o, k) {
        o[k] = o[k] ? o[k] + 1 : 1;
        return o;
      }, {});
    
      // find those that only appeared once
      return Object.keys(counts).filter(function(k) {
        return (counts[k] === 1);
      });
    }
    
    console.log(
      uniq(['txfa2', 'txfa9', 'txfa2', 'txfa1', 'txfa3', 'txfa4', 'txfa8', 'txfa9', 'txfa2', 'txfa8'])
    )

    Working demo at http://jsfiddle.net/alnitak/shyce/

提交回复
热议问题