目前,我有一个这样的数组:
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
等等
const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)
像这样的东西:
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);
如果您不希望它在旧浏览器中中断,请使用简单的 for 循环而不是 forEach。
我偶然发现了这个(非常古老的)问题。有趣的是,缺少最明显和最优雅的解决方案(恕我直言):Array.prototype.reduce(...)。自 2011 年左右(IE)或更早(所有其他)以来,所有主要浏览器都支持此功能:
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:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
编辑:
通过在箭头函数中使用逗号运算符,我们可以用一行代码编写它:
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce((cnt, cur) => (cnt[cur] = cnt[cur] + 1 || 1, cnt), {});
// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
但是,由于这可能更难阅读/理解,因此应该坚持使用第一个版本。
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');
}
}
count();
您也可以使用高阶函数来执行操作。 看到这个答案
简单更好,一个变量,一个函数:)
const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {});
console.log(counts);
基于reduce数组函数的单行
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));
// Initial array
let array = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a'];
// Unique array without duplicates ['a', 'b', ... , 'h']
let unique = [...new Set(array)];
// This array counts duplicates [['a', 3], ['b', 2], ... , ['h', 3]]
let duplicates = unique.map(value => [value, array.filter(str => str === value).length]);
似乎没有人对此使用Map()
内置的响应,这往往是我的首选结合Array.prototype.reduce()
:
const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());
console.log(...result);
注意,如果想在旧版浏览器中使用它,则必须进行polyfill 。Map()
您可以拥有一个包含计数的对象。遍历列表并增加每个元素的计数:
var counts = {};
uniqueCount.forEach(function(element) {
counts[element] = (counts[element] || 0) + 1;
});
for (var element in counts) {
console.log(element + ' = ' + counts[element]);
}
我认为这是如何计算数组中具有相同值的出现的最简单方法。
var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
您可以在不使用任何 for/while 循环或 forEach 的情况下解决它。
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
希望对你有帮助!
// new example.
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];
function findOdd(para) {
var count = {};
para.forEach(function(para) {
count[para] = (count[para] || 0) + 1;
});
return count;
}
console.log(findOdd(str));
const obj = {};
const uniqueCount = [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'f', 'g', 'h', 'h', 'h', 'e', 'a' ];
for (let i of uniqueCount) obj[i] ? obj[i]++ : (obj[i] = 1);
console.log(obj);
你可以这样做:
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;
}
}
现在你有一张包含所有字符数的地图
在javascript中使用数组reduce方法很简单:
const arr = ['a','d','r','a','a','f','d'];
const result = arr.reduce((json,val)=>({...json, [val]:(json[val] | 0) + 1}),{});
console.log(result)
//{ a:3,d:2,r:1,f:1 }
代码:
function getUniqueDataCount(objArr, propName) {
var data = [];
if (Array.isArray(propName)) {
propName.forEach(prop => {
objArr.forEach(function(d, index) {
if (d[prop]) {
data.push(d[prop]);
}
});
});
} else {
objArr.forEach(function(d, index) {
if (d[propName]) {
data.push(d[propName]);
}
});
}
var uniqueList = [...new Set(data)];
var dataSet = {};
for (var i = 0; i < uniqueList.length; i++) {
dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
}
return dataSet;
}
片段
var data= [
{day:'Friday' , name: 'John' },
{day:'Friday' , name: 'John' },
{day:'Friday' , name: 'Marium' },
{day:'Wednesday', name: 'Stephanie' },
{day:'Monday' , name: 'Chris' },
{day:'Monday' , name: 'Marium' },
];
console.log(getUniqueDataCount(data, ['day','name']));
function getUniqueDataCount(objArr, propName) {
var data = [];
if (Array.isArray(propName)) {
propName.forEach(prop => {
objArr.forEach(function(d, index) {
if (d[prop]) {
data.push(d[prop]);
}
});
});
} else {
objArr.forEach(function(d, index) {
if (d[propName]) {
data.push(d[propName]);
}
});
}
var uniqueList = [...new Set(data)];
var dataSet = {};
for (var i = 0; i < uniqueList.length; i++) {
dataSet[uniqueList[i]] = data.filter(x => x == uniqueList[i]).length;
}
return dataSet;
}
uniqueCount = ["a","b","a","c","b","a","d","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach((i) => { count[i] = ++count[i]|| 1});
console.log(count);
包含字母的数组中的重复项:
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>");
}
包含数字的数组中的重复项:
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>");
}
简化的 sheet.js 答案
var counts = {};
var aarr=['a','b','a'];
aarr.forEach(x=>counts[x]=(counts[x] || 0)+1 );
console.log(counts)
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}`);
}
var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h ','h','h','e','a'];
var newArr = [];
testArray.forEach((item) => {
newArr[item] = testArray.filter((el) => {
return el === item;
}).length;
})
console.log(newArr);
好答案的组合:
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]);
}
}
希望它有帮助。
例如创建一个文件demo.js
并在控制台中使用节点运行它,demo.js
您将以矩阵的形式出现元素。
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);
您将在控制台中获得如下结果:
[ 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 ] ]
最快的方法:
计算复杂度为 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']);
声明一个对象arr
来保存唯一集作为键。使用 map 循环遍历数组来填充arr
。如果之前没有找到该键,则添加该键并分配零值。在每次迭代中增加键的值。
给定测试数组:
var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
解决方案:
var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});
JSON.stringify(arr)
将输出
{"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}
Object.keys(arr)
将返回["a","b","c","d","e","f","g","h"]
要查找任何项目的出现,例如 barr['b']
将输出2
通过使用 array.map 我们可以减少循环,请参阅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;
}
去测试:
var test = new Check(1,2,1,4,1);
console.log(test);
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
*/
示例如何返回字符串中最常用的字符。
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'))
let arr=[1,2,3,3,4,5,5,6,7,7]
let obj={}
for(var i=0;i<arr.length;i++){
obj[arr[i]]=obj[arr[i]]!=null ?obj[arr[i]]+1:1 //stores duplicate in an obj
}
console.log(obj)
//returns object {1:1,:1,3:2,.....}
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;
}
Str= ['a','b','c','d','d','e','a','h','e','a'];
var obj= new Object();
for(var i = 0; i < Str.length; i++) {
if(obj[Str[i]] != null) {
obj[Str[i]] += 1;
} else {
obj[Str[i]] = 1;
}
}
console.log(obj);
现在您可以获得重复项目的地图
计算字符串中提供的字母
function countTheElements(){
var str = "ssdefrcgfrdesxfdrgs";
var arr = [];
var count = 0;
for(var i=0;i<str.length;i++){
arr.push(str[i]);
}
arr.sort();
for(var i=0;i<arr.length;i++){
if(arr[i] == arr[i-1]){
count++;
}else{
count = 1;
}
if(arr[i] != arr[i+1]){
console.log(arr[i] +": "+(count));
}
}
}
countTheElements()
您可以使用 array.reduce() 方法简单地做到这一点
const votes = ['Yes', 'Yes', 'Yes', 'No', 'No', 'Absent'];
const result = votes.reduce((prevValue, vote) => {
if (prevValue[vote]) {
prevValue[vote]++;
} else {
prevValue[vote] = 1;
}
return prevValue;
}, {});
console.log(result);
输出:{是:3,否:2,缺席:1}
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");
}
}