Currently, I got an array like that:
var uniqueCount = Array();
After a few steps, my array looks like that:
uniqueCount =
// 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));
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>");
}
Simple is better, one variable, one function :)
const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 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();
Demo Fiddle
You can use higher-order functions too to do the operation. See this answer