查找在Javascript数组中只出现一次的项目

Wer*_*eta 3 javascript arrays jquery

我正在尝试找到在Javascript数组中只出现一次的项目.在以下数组中:

['txfa2','txfa9','txfa2','txfa1','txfa3','txfa4','txfa8','txfa9','txfa2','txfa8']
Run Code Online (Sandbox Code Playgroud)

结果应该是:

['txfa1','txfa3','txfa4']
Run Code Online (Sandbox Code Playgroud)

我目前正在.each()jQuery中使用该函数.sort().这样做有更聪明或更好的方法吗?你知道任何jQuery插件可以用更少的代码行完成.

<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>
Run Code Online (Sandbox Code Playgroud)

Aln*_*tak 6

这是使用ES5的功能方法的示例,基于使用对象来计算每个值发生的次数:

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'])
)
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/alnitak/shyce/的工作演示


Thi*_*iff 5

一个简洁的方法:

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 ))
Run Code Online (Sandbox Code Playgroud)

演示: http: //jsfiddle.net/ThinkingStiff/C849F/

这是该问题的非重复答案(实际有效)的性能,表明该方法(蓝色)与其他方法具有可比性。

性能:http://jsperf.com/find-array-singles/3

在此输入图像描述