查找在Javascript数组中仅出现一次的项目 [英] Finding items that appear only one time in a Javascript array
问题描述
我试图找到在Javascript数组中仅出现一次的项目.在以下数组中:
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']
结果应为:
['txfa1','txfa3','txfa4']
我目前在jQuery和.sort()
中使用.each()
函数.是否有更聪明或更好的方法来做到这一点?您是否知道可以用更少的代码行做到这一点的jQuery插件.
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>
推荐答案
一种简洁的方法:
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 ))
演示: 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.
性能: http://jsperf.com/find-array-singles/3
这篇关于查找在Javascript数组中仅出现一次的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!