目前,我有一个数组如下:
var uniqueCount = Array();
几步之后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
我该如何计算数组中有多少个a、b、c?我希望得到这样的结果:a = 3
b = 1
c = 2
d = 2
目前,我有一个数组如下:
var uniqueCount = Array();
几步之后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
我该如何计算数组中有多少个a、b、c?我希望得到这样的结果:a = 3
b = 1
c = 2
d = 2
最快的方法:
计算复杂度为O(n)。
function howMuchIsRepeated_es5(arr) {
const count = {};
for (let i = 0; i < arr.length; i++) {
const val = arr[i];
if (val in count) {
count[val] = count[val] + 1;
} else {
count[val] = 1;
}
}
for (let key in count) {
console.log("Value " + key + " is repeated " + count[key] + " times");
}
}
howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
最短的代码:
使用ES6。
function howMuchIsRepeated_es6(arr) {
// count is [ [valX, count], [valY, count], [valZ, count]... ];
const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);
for (let i = 0; i < count.length; i++) {
console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);
}
}
howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
返回字符串中最常用的字符的示例。
function maxChar(str) {
const charMap = {};
let maxCharacter = '';
let maxNumber = 0;
for (let item of str) {
charMap[item] = charMap[item] + 1 || 1;
}
for (let char in charMap) {
if (charMap[char] > maxNumber) {
maxNumber = charMap[char];
maxCharacter = char;
}
}
return maxCharacter;
}
console.log(maxChar('abcccccccd'))
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
*/
var arr = ['a','d','r','a','a','f','d'];
//call function and pass your array, function will return an object with array values as keys and their count as the key values.
duplicatesArr(arr);
function duplicatesArr(arr){
var obj = {}
for(var i = 0; i < arr.length; i++){
obj[arr[i]] = [];
for(var x = 0; x < arr.length; x++){
(arr[i] == arr[x]) ? obj[arr[i]].push(x) : '';
}
obj[arr[i]] = obj[arr[i]].length;
}
console.log(obj);
return obj;
}
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");
}
}
{}
这种类型的map,而不是函数式编程中的map
。 - Matt Ball