我正在尝试查找在 Javascript 数组中只出现一次的项目。在以下数组中:
['txfa2','txfa9','txfa2','txfa1','txfa3','txfa4','txfa8','txfa9','txfa2','txfa8']
结果应该是:
['txfa1','txfa3','txfa4']
我目前在 jQuery 和 .sort()
中使用 .each()
函数。这样做有更聪明或更好的方法吗?你知道有什么 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>
最佳答案
下面是一个使用 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'])
)
关于javascript - 查找在 Javascript 数组中只出现一次的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8699357/