如何在 JavaScript 中创建唯一项目列表? [英] How to create a list of unique items in JavaScript?

查看:30
本文介绍了如何在 JavaScript 中创建唯一项目列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 CouchDB 缩减功能中,我需要将项目列表缩减为唯一的项目.

In my CouchDB reduce function I need to reduce a list of items to the unique ones.

注意:在这种情况下,可以有一个列表,它将是少数字符串类型的项目.

我目前的方法是设置一个对象的键,然后返回那个对象的键因为代码不能使用诸如 _.uniq 之类的东西.

My current way is to set keys of a object, then return the keys of that object since the place the code can't use things like _.uniq for example.

我想找到比这更优雅的拼写方式.

I'd like to find a more elegant way to spell it than this.

function(keys, values, rereduce) {
  // values is a Array of Arrays
  values = Array.concat.apply(null, values);
  var uniq = {};
  values.forEach(function(item) { uniq[item] = true; });
  return Object.keys(uniq);
}

推荐答案

通常,您使用的方法是一个好主意.但我可以提出一个解决方案,让算法更快.

Commonly, the approach you used is a good idea. But I could propose a solution that will make the algorithm a lot faster.

function unique(arr) {
    var u = {}, a = [];
    for(var i = 0, l = arr.length; i < l; ++i){
        if(!u.hasOwnProperty(arr[i])) {
            a.push(arr[i]);
            u[arr[i]] = 1;
        }
    }
    return a;
}

如您所见,我们这里只有一个循环.

As you can see we have only one loop here.

我制作了一个 示例,用于测试您和我的解决方案.试试看吧.

I've made an example that is testing both your and my solutions. Try to play with it.

这篇关于如何在 JavaScript 中创建唯一项目列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆