javascript 计算数组中的唯一元素而不进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15052702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count unique elements in array without sorting
提问by Ghoul Fool
In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array
在 JavaScript 中,以下将找到数组中元素的数量。假设数组中至少有一个元素
arr = ["jam", "beef", "cream", "jam"]
arr.sort();
var count = 1;
var results = "";
for (var i = 0; i < arr.length; i++)
{
if (arr[i] == arr[i+1])
{
count +=1;
}
else
{
results += arr[i] + " --> " + count + " times\n" ;
count=1;
}
}
Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting. And yes, I'm an artist, not a programmer, your honour.
是否可以在不使用 sort() 或不以任何方式改变数组的情况下执行此操作?我想必须重新创建数组,然后可以对新创建的数组进行排序,但我想知道不排序的最佳方法是什么。是的,我是一名艺术家,而不是程序员,您的荣幸。
回答by kojiro
A quick way to do this is to copy the unique elements into an Object.
一个快速的方法是将唯一元素复制到一个对象中。
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
When this loop is complete the counts
object will have the count of each distinct element of the array.
当这个循环完成时,counts
对象将拥有数组中每个不同元素的计数。
回答by Web_Designer
The fast way to do this is with a new Set()
object.
执行此操作的快速方法是使用new Set()
对象。
Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js.
— What is faster Set or Object?by Andrei Kashcha
集合很棒,我们应该更频繁地使用它们。它们速度很快,并受 Chrome、Firefox、Microsoft Edge 和 node.js 支持。
— Set 或 Object 哪个更快?通过安德烈·卡什查
The items in a Set
will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:
a 中的项目Set
将始终是唯一的,因为它只保留您输入的每个值的一个副本。这是一个使用此属性的函数:
function countUnique(iterable) {
return new Set(iterable).size;
}
console.log(countUnique('banana')); //=> 3
console.log(countUnique([5,6,5,6])); //=> 2
console.log(countUnique([window, document, window])); //=> 2
This can be used to count the items in any iterable(including an Array, String, TypedArray, and arguments object).
这可用于计算任何可迭代对象(包括 Array、String、TypedArray 和 arguments 对象)中的项目。
回答by Ash Catchem
Why not something like:
为什么不是这样的:
var arr = ["jam", "beef", "cream", "jam"]
var uniqs = arr.reduce((acc, val) => {
acc[val] = acc[val] === undefined ? 1 : acc[val] += 1;
return acc;
}, {});
console.log(uniqs)
Pure Javascript, runs in O(n). Doesn't consume much space either unless your number of unique values equals number of elements (all the elements are unique).
纯 Javascript,在O(n) 中运行。除非您的唯一值数等于元素数(所有元素都是唯一的),否则也不会占用太多空间。
回答by Plynx
This expression gives you all the unique elements in the array without mutating it:
此表达式为您提供数组中的所有唯一元素,而不会对其进行变异:
arr.filter(function(v,i) { return i==arr.lastIndexOf(v); })
You can chain it with this expression to build your string of results without sorting:
您可以使用此表达式链接它以构建您的结果字符串而无需排序:
.forEach(function(v) {
results+=v+" --> " + arr.filter(function(w){return w==v;}).length + " times\n";
});
In the first case the filter takes only includes the last of each specific element; in the second case the filter includes all the elements of that type, and .length
gives the count.
在第一种情况下,过滤器只包含每个特定元素的最后一个;在第二种情况下,过滤器包括该类型的所有元素,并.length
给出计数。
回答by kryptoatom
Same as this solution, but less code.
与此解决方案相同,但代码更少。
let counts = {};
arr.forEach(el => counts[el] = 1 + (counts[el] || 0))