Currently, I got an array like that:
var uniqueCount = Array();
After a few steps, my array looks like that:
uniqueCount =
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 ] ]
It is simple in javascript using array reduce method:
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 }
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
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);
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.
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
*/