最优雅的方式来创建在JavaScript中唯一项的列表 [英] Most elegant way to create a list of unique items in JavaScript
问题描述
在我的CouchDB减少功能我需要减少项目的列表,以独特的人。
的注:在这种情况下,它的确定有一个列表,这将是字符串类型的项目少数的
我目前的方法是设置密钥的对象,然后返回该对象的钥匙
自code不能使用像 _东西的地方。uniq的
例如
我想找到一个更优雅的方式来拼写莫过于此。
功能(键,值rereduce){
//值是数组的数组一
值= Array.concat.apply(NULL,值);
变种的uniq = {};
values.forEach(函数(项目){uniq的[项目] =真;});
返回Object.keys(uniq的);
}
通常情况下,你使用的方法是一个好主意。
但是,我可以提出一个解决方案,使算法快了很多。
功能独特(ARR){
变种U = {},A = [];
对于(VAR I = 0,1 = arr.length; I<升; ++ I){
如果(!u.hasOwnProperty(ARR [I])){
a.push(ARR [I]);
U [ARR [I] = 1;
}
}
返回;
}
正如你可以看到我们这里只有一个循环。
我做了一个 示例 即同时测试你的和我的解决方案。尝试用它来播放。
In my CouchDB reduce function I need to reduce a list of items to the unique ones.
Note: In that case it's ok to have a list, it will be a small number of items of string type.
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屋!