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

标签 javascript jquery arrays

我正在尝试查找在 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'])
)

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

关于javascript - 查找在 Javascript 数组中只出现一次的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8699357/

相关文章:

jQuery 1.8 位置无法正常工作

jQuery UI 对话框调用在 MVC 3 中返回 HttpContect 响应流的操作

Javascript - 获取数组中数组最大和的最佳方法

javascript - z-index 不能在侧边导航上工作

javascript - 无法使用 chrome 43 beta 设置 xhr.responseType

javascript - 从 TinyMCE 内容动态填充一个 div

javascript - 如何使用 Astronomy 的父属性验证表单 - MeteorJS

javascript - JQuery 数据表在初始化后突出显示行

php - 如何将 PHP7 的 $mysqli->real_escape_string 与数组一起使用

c - 在 C 中将字符串从数组传递到函数指针