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
等。
#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');
}
}
count();
演示小提琴
您也可以使用高阶函数进行操作。查看此答案
评论
循环后多余的if语句是不必要的...仅用于(var i = 0; i <= array_elements.length; i ++){或<=而不是<。
– EmmaGamma
2015年2月9日,下午1:58
嗨@Vinay,也许您可以在这里帮我吗? stackoverflow.com/questions/57819850 / ...
– SMPLYJR
19-09-6在10:05
#2 楼
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
评论
这绝对是最简单的答案
–Josh Beam
2015年12月3日23:37
(counts [x] || 0)+1这怎么给count?
–jsduniya
17年1月2日,17:30
@SidBhalke:表达式很重要[x] ||如果设置为0,则返回counts [x]的值,否则返回0。然后只加一个并在对象中再次设置即可完成计数。
–Constantinius
17-2-7在11:52
@SheetJS,如果您想知道为什么投票失败-是我;我在移动设备上浏览时,没有实际注意到点击了按钮。一旦发现,现在就来不及了。对此表示歉意,答案确实很好。如果您要编辑它,我很乐意撤消。
– Todor Minakov
19年1月19日在10:17
还带有reduce:var counts = your_array.reduce((map,val)=> {map [val] =(map [val] || 0)+1; return map},{});
– Alberto89
19年5月17日在8:29
#3 楼
像这样的东西: 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。
评论
@web_dev他创建了一个名为count的关联数组对象,该数组对象将为数组中的每个唯一元素具有一个键值对,其中键是唯一元素值,而值是count。他遍历数组,并为每个值增加值或创建键值对(不存在的键的值求值为undefined,因此||或运算符取零,然后加1)。
–robisrob
16年7月9日,下午3:17
@neelmeg也许为“ forEach”编写所有参数有助于更好地理解(“ i”是每个数组值,而不是它的索引):uniqueCount.forEach(function(value,index){count [value] =(count [value] | | 0)+ 1;});
–佩德罗·费雷拉(Pedro Ferreira)
17年4月4日在23:15
什么是采取额外步骤并按总数计数的好方法?
–震颤
9月11日20:27
#4 楼
我偶然发现了这个(非常古老的)问题。有趣的是,缺少了最明显,最优雅的解决方案(imho):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:
document.write(JSON.stringify(map));
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
#5 楼
基于减少数组功能的单行 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));
评论
我刚刚意识到@ isnot2bad(stackoverflow.com/a/32886673/621058)与我的几乎相同。我只是碰巧使用粗箭头功能和常量
–迪尼哥
17年11月9日在11:51
#6 楼
简单更好,一个变量,一个函数:)const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {});
#7 楼
我认为这是最简单的方法来计算数组中具有相同值的出现次数。var a = [true, false, false, false];
a.filter(function(value){
return value === false;
}).length
#8 楼
似乎没有人对此使用内置的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);
注意,如果要在较旧的浏览器中使用它,则必须填充
Map()
。评论
您能否深入解释一下它是如何工作的? (特别是set / get部分)。我试图将reducer分解为一个函数,但是我得到的“ get”不是一个响应函数。
– Antoine Nedelec
5月7日7:32
Ok get和set函数来自Map对象。但是初始累加器不是Map对象,那么为什么reducer的简化版本需要一个?
– Antoine Nedelec
5月7日7:39
@AntoineNedelec初始值为一个新的Map对象;参见reduce的第二个参数。 Map.prototype.set返回地图对象,而Map.prototype.get返回未定义或提供给它的任何键的值。这使我们可以获取每个字母的当前计数(如果未定义,则为0),然后将其递增一,然后将该字母的计数设置为新计数,这将返回映射并成为新的累加器值。
– aendrew
5月18日20:13
#9 楼
// 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]);
#10 楼
您可以有一个包含计数的对象。遍历列表并增加每个元素的计数:var counts = {};
uniqueCount.forEach(function(element) {
counts[element] = (counts[element] || 0) + 1;
});
for (var element in counts) {
console.log(element + ' = ' + counts[element]);
}
评论
您为什么要设置此条件计数[元素] || 0?
–问人
6月12日12:06
第一次访问counts [element]返回的结果是undefined,因为该属性还没有值。如果然后尝试添加undefined + 1,则结果将为NaN。 (count [element] || 0)会将undefined替换为0,因此加1会生成1而不是NaN。 ECMAScript 2020添加了无效的合并运算符??它做类似的事情,但更明确的一点是,当第一个值未定义(或为null)时,它将使用第二个值。该版本为(counts [element] ?? 0)+ 1。
– nkron
9月9日6:18
#11 楼
您可以解决它,而无需使用forEach的任何for / while循环。function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
希望它对您有所帮助!
#12 楼
// 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));
#13 楼
您可以执行以下操作: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;
}
}
现在您已经有了一个包含所有字符数的地图
#14 楼
在javascript中,使用数组化简方法很简单: 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 }
#15 楼
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}`);
}
评论
感谢您对其进行更新,这对那些开始的人有很大帮助。
–Regular Joe
17 Mar 25 '17在17:36
#16 楼
包含字母的数组中的重复项: 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>");
}
#17 楼
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);
#18 楼
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);
#19 楼
简化的sheet.js answare var counts = {};
var aarr=['a','b','a'];
aarr.forEach(x=>counts[x]=(counts[x] || 0)+1 );
console.log(counts)
#20 楼
好答案的组合: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]);
}
}
希望有帮助。
#21 楼
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");
}
}
评论
您可以围绕此添加一些上下文吗?
– Neo
17年7月19日在14:35
#22 楼
通过使用array.map,我们可以减少循环,请参见jsfiddlefunction 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);
#23 楼
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
*/
#24 楼
创建一个文件,例如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 ] ]
#25 楼
最快的方法:计算复杂度为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']);
#26 楼
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;
}
#27 楼
声明一个对象arr
以保留唯一集作为键。通过使用map循环遍历数组来填充arr
。如果先前未找到密钥,则添加密钥并分配零值。在每次迭代中,增加密钥的值。 给出testArray:
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)
将返回Object.keys(arr)
查找任何项的出现,例如b
["a","b","c","d","e","f","g","h"]
将输出arr['b']
评论
请不要仅发布代码作为答案,还请提供解释,说明代码的作用以及如何解决问题。附有解释的答案通常质量较高,并且更有可能吸引投票。
– Mark Rotteveel
19-10-19在7:01
#28 楼
用法:wrap.common.getUniqueDataCount(, columnName);
代码:
function getUniqueDataCount(objArr, propName) {
var data = [];
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= [
{a:'you',b:'b',c:'c',d:'c'},
{a: 'you', b: 'b', c: 'c', d:'c'},
{a: 'them', b: 'b', c: 'c', d:'c'},
{a: 'them', b: 'b', c: 'c', d:'c'},
{a: 'okay', b: 'b', c: 'c', d:'c'},
{a: 'okay', b: 'b', c: 'c', d:'c'},
];
console.log(getUniqueDataCount(data, 'a'));
function getUniqueDataCount(objArr, propName) {
var data = [];
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;
}
评论
stackoverflow.com/questions/12749200 / ...的可能重复项...@Nirk我认为,musical_coder的意思是{}中的映射,而不是函数式编程的映射。