Ron*_*nny 12 javascript arrays couchdb
在我的CouchDB reduce函数中,我需要将项目列表减少到唯一的项目.
注意:在这种情况下,可以有一个列表,它将是少量的字符串类型的项目.
我目前的方法是设置一个对象的键,然后返回该对象的键,因为代码不能使用这样的地方_.uniq.
我想找一个更优雅的拼写方法.
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);
}
Run Code Online (Sandbox Code Playgroud)
Eug*_*nov 26
通常,您使用的方法是个好主意.但我可以提出一个解决方案,使算法更快.
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;
}
Run Code Online (Sandbox Code Playgroud)
如你所见,我们这里只有一个循环.
我做了一个测试你和我的解决方案的例子.尝试玩它.
Joa*_*ger 10
最好的方法似乎是使用ES6和Set.根据小提琴单线和快*以上*
const myList = [1,4,5,1,2,4,5,6,7];
const unique = [...new Set(myList)];
console.log(unique);Run Code Online (Sandbox Code Playgroud)
*在野生动物园测试
适合小型列表的另一种方法是使用Unix命令行方法sort | uniq:
function unique(a) {
return a.sort().filter(function(value, index, array) {
return (index === 0) || (value !== array[index-1]);
});
}
Run Code Online (Sandbox Code Playgroud)
此函数对参数进行排序,然后过滤结果以省略与其前一个项相同的任何项.
基于密钥的方法很好,并且对于大量项目将具有更好的性能特征(O(n)用于将n个项目插入哈希表中,与用于对数组进行排序的O(n log n)相比).但是,这在小型名单上不太可能引人注意.此外,使用此版本,您可以修改它以在必要时使用不同的排序或相等功能; 使用哈希键,你会遇到JavaScripts密钥相等的概念.
这应该适用于任何东西,而不仅仅是字符串:
export const getUniqueList = (a: Array<any>) : Array<any> => {
const set = new Set<any>();
for(let v of a){
set.add(v);
}
return Array.from(set);
};
Run Code Online (Sandbox Code Playgroud)
以上可以简化为:
export const getUniqueValues = (a: Array<any>) => {
return Array.from(new Set(a));
};
Run Code Online (Sandbox Code Playgroud)
:)
| 归档时间: |
|
| 查看次数: |
31447 次 |
| 最近记录: |