可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Currently, I got an array like that:
var uniqueCount = Array();
After a few steps, my array looks like that:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
How can I count how many a,b,c are there in the array? I want to have a result like:
a = 3
b = 1
c = 2
d = 2
etc.
回答1:
function count() {
array_elements = [\"a\", \"b\", \"c\", \"d\", \"e\", \"a\", \"b\", \"c\", \"f\", \"g\", \"h\", \"h\", \"h\", \"e\", \"a\"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + \' comes --> \' + cnt + \' times<br>\');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + \' comes --> \' + cnt + \' times\');
}
}
Demo Fiddle
回答2:
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
回答3:
Something like this:
uniqueCount = [\"a\",\"b\",\"c\",\"d\",\"d\",\"e\",\"a\",\"b\",\"c\",\"f\",\"g\",\"h\",\"h\",\"h\",\"e\",\"a\"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
Use a simple for loop instead of forEach if you don\'t want this to break in older browsers.
回答4:
I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):
var arr = [\'a\',\'b\',\'c\',\'d\',\'d\',\'e\',\'a\',\'b\',\'c\',\'f\',\'g\',\'h\',\'h\',\'h\',\'e\',\'a\'];
var map = arr.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
// map is an associative array mapping the elements to their frequency:
document.write(JSON.stringify(map));
// prints {\"a\": 3, \"b\": 2, \"c\": 2, \"d\": 2, \"e\": 2, \"f\": 1, \"g\": 1, \"h\": 3}
回答5:
Single line based on reduce array function
const uniqueCount = [\"a\", \"b\", \"c\", \"d\", \"d\", \"e\", \"a\", \"b\", \"c\", \"f\", \"g\", \"h\", \"h\", \"h\", \"e\", \"a\"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] | 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));
回答6:
I think this is the simplest way how to count occurrences with same value in array.
var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
回答7:
You can solve it without using any for/while loops ou forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
回答8:
You can do something like that:
uniqueCount = [\'a\',\'b\',\'c\',\'d\',\'d\',\'e\',\'a\',\'b\',\'c\',\'f\',\'g\',\'h\',\'h\',\'h\',\'e\',\'a\'];
var map = new Object();
for(var i = 0; i < uniqueCount.length; i++) {
if(map[uniqueCount[i]] != null) {
map[uniqueCount[i]] += 1;
} else {
map[uniqueCount[i]] = 1;
}
}
now you have a map with all characters count
回答9:
You can have an object that contains counts. Walk over the list and increment the count for each element:
var counts = {};
uniqueCount.forEach(function(element) {
counts[element] = (counts[element] || 0) + 1;
});
for (var element in counts) {
console.log(element + \' = \' + counts[element]);
}
回答10:
var uniqueCount = [\'a\',\'b\',\'c\',\'d\',\'d\',\'e\',\'a\',\'b\',\'c\',\'f\',\'g\',\'h\',\'h\',\'h\',\'e\',\'a\'];
// here we will collect only unique items from the array
var uniqueChars = [];
// iterate through each item of uniqueCount
for (i of uniqueCount) {
// if this is an item that was not earlier in uniqueCount,
// put it into the uniqueChars array
if (uniqueChars.indexOf(i) == -1) {
uniqueChars.push(i);
}
}
// after iterating through all uniqueCount take each item in uniqueChars
// and compare it with each item in uniqueCount. If this uniqueChars item
// corresponds to an item in uniqueCount, increase letterAccumulator by one.
for (x of uniqueChars) {
let letterAccumulator = 0;
for (i of uniqueCount) {
if (i == x) {letterAccumulator++;}
}
console.log(`${x} = ${letterAccumulator}`);
}
回答11:
A combination of good answers:
var count = {};
var arr = [\'a\', \'b\', \'c\', \'d\', \'d\', \'e\', \'a\', \'b\', \'c\', \'f\', \'g\', \'h\', \'h\', \'h\', \'e\', \'a\'];
var iterator = function (element) {
count[element] = (count[element] || 0) + 1;
}
if (arr.forEach) {
arr.forEach(function (element) {
iterator(element);
});
} else {
for (var i = 0; i < arr.length; i++) {
iterator(arr[i]);
}
}
Hope it\'s helpful.
回答12:
public class CalculateCount {
public static void main(String[] args) {
int a[] = {1,2,1,1,5,4,3,2,2,1,4,4,5,3,4,5,4};
Arrays.sort(a);
int count=1;
int i;
for(i=0;i<a.length-1;i++){
if(a[i]!=a[i+1]){
System.out.println(\"The Number \"+a[i]+\" appears \"+count+\" times\");
count=1;
}
else{
count++;
}
}
System.out.println(\"The Number \"+a[i]+\" appears \"+count+\" times\");
}
}
回答13:
Duplicates in an array containing alphabets:
var arr = [\"a\", \"b\", \"a\", \"z\", \"e\", \"a\", \"b\", \"f\", \"d\", \"f\"],
sortedArr = [],
count = 1;
sortedArr = arr.sort();
for (var i = 0; i < sortedArr.length; i = i + count) {
count = 1;
for (var j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i] === sortedArr[j])
count++;
}
document.write(sortedArr[i] + \" = \" + count + \"<br>\");
}
Duplicates in an array containing numbers:
var arr = [2, 1, 3, 2, 8, 9, 1, 3, 1, 1, 1, 2, 24, 25, 67, 10, 54, 2, 1, 9, 8, 1],
sortedArr = [],
count = 1;
sortedArr = arr.sort(function(a, b) {
return a - b
});
for (var i = 0; i < sortedArr.length; i = i + count) {
count = 1;
for (var j = i + 1; j < sortedArr.length; j++) {
if (sortedArr[i] === sortedArr[j])
count++;
}
document.write(sortedArr[i] + \" = \" + count + \"<br>\");
}
回答14:
By using array.map we can reduce the loop, see this on jsfiddle
function Check(){
var arr = Array.prototype.slice.call(arguments);
var result = [];
for(i=0; i< arr.length; i++){
var duplicate = 0;
var val = arr[i];
arr.map(function(x){
if(val === x) duplicate++;
})
result.push(duplicate>= 2);
}
return result;
}
To Test:
var test = new Check(1,2,1,4,1);
console.log(test);
回答15:
var string = [\'a\',\'a\',\'b\',\'c\',\'c\',\'c\',\'c\',\'c\',\'a\',\'a\',\'a\'];
function stringCompress(string){
var obj = {},str = \"\";
string.forEach(function(i) {
obj[i] = (obj[i]||0) + 1;
});
for(var key in obj){
str += (key+obj[key]);
}
console.log(obj);
console.log(str);
}stringCompress(string)
/*
Always open to improvement ,please share
*/
回答16:
Create a file for example demo.js
and run it in console with node demo.js
and you will get occurrence of elements in the form of matrix.
var multipleDuplicateArr = Array(10).fill(0).map(()=>{return Math.floor(Math.random() * Math.floor(9))});
console.log(multipleDuplicateArr);
var resultArr = Array(Array(\'KEYS\',\'OCCURRENCE\'));
for (var i = 0; i < multipleDuplicateArr.length; i++) {
var flag = true;
for (var j = 0; j < resultArr.length; j++) {
if(resultArr[j][0] == multipleDuplicateArr[i]){
resultArr[j][1] = resultArr[j][1] + 1;
flag = false;
}
}
if(flag){
resultArr.push(Array(multipleDuplicateArr[i],1));
}
}
console.log(resultArr);
You will get result in console as below:
[ 1, 4, 5, 2, 6, 8, 7, 5, 0, 5 ] . // multipleDuplicateArr
[ [ \'KEYS\', \'OCCURENCE\' ], // resultArr
[ 1, 1 ],
[ 4, 1 ],
[ 5, 3 ],
[ 2, 1 ],
[ 6, 1 ],
[ 8, 1 ],
[ 7, 1 ],
[ 0, 1 ] ]
回答17:
This is my dummy answer that anyone can understand!
const duplicates = function(arr){
const dic = []
arr.forEach(function(val){
if(!!dic[val]){
dic[val]++
}else{
dic[val] = 1
}
});
return dic
}