180

Currently, I got an array like that:

var uniqueCount = Array();

After a few steps, my array looks like that:

uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];

How can I count how many a,b,c are there in the array? I want to have a result like:

a = 3
b = 1
c = 2
d = 2

etc.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
detno29
  • 2,113
  • 6
  • 19
  • 21

35 Answers35

457

const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
SheetJS
  • 22,470
  • 12
  • 65
  • 75
  • 14
    This is definitely the simplest answer – Josh Beam Dec 03 '15 at 23:37
  • 7
    (counts[x] || 0)+1 how this is giving count ? – jsduniya Jan 02 '17 at 17:30
  • 8
    @SidBhalke: The expression `counts[x] || 0` returns the value of `counts[x]` if it is set, otherwise `0`. Then just add one and set it again in the object and the count is done. – Constantinius Feb 07 '17 at 11:52
  • 3
    @SheetJS if you're wondering why the downvote - it was me; I was browsing on mobile, and have clicked the button w/o actually noticing. Once I found out it was too late to revert. Apologies for that, the answer is really good. If you want to edit it, I'd be glad to reverse. – Todor Minakov Jan 19 '19 at 10:17
  • 12
    Also with `reduce`: `var counts = your_array.reduce((map, val) => {map[val] = (map[val] || 0)+1; return map}, {} );` – Alberto89 May 17 '19 at 08:29
  • Just wanted to say this was the most helpful solution I found. – Rokas Lakštauskas May 05 '20 at 13:19
  • Any special reason to use `const` instead of `var` or `let`? – Rodrigo Jun 26 '21 at 20:56
96

Something like this:

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);

Use a simple for loop instead of forEach if you don't want this to break in older browsers.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
loxxy
  • 12,990
  • 2
  • 25
  • 56
  • 6
    @web_dev he creates an associative array object called count that will have a key value pair for each unique element in the array, where the key is the unique element value and the value is the count. He iterates over the array and for each value either increments the value or creates the key value pair (the value of the non-existent key evaluates to undefined so the || or operator takes a zero instead and adds the 1) – robisrob Jul 09 '16 at 03:17
  • 1
    @neelmeg Maybe writing all parameters for "forEach" helps better to understand ("i" is each array value and NOT it's índex): `uniqueCount.forEach(function(value, index) { count[value] = (count[value] || 0) + 1; }); ` – Pedro Ferreira Apr 04 '17 at 23:15
  • what would be a good way to go an extra step and sort by count total? – tremor Sep 11 '20 at 20:27
78

I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):

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}

EDIT:

By using the comma operator in an arrow function, we can write it in one single line of code:

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}

However, as this may be harder to read/understand, one should probably stick to the first version.

isnot2bad
  • 24,105
  • 2
  • 29
  • 50
  • Is there a different way of doing this without the erroneous parameter reassignment? `prev[cur] = (prev[cur] || 0) + 1;` – keyboard-warrior Sep 29 '21 at 13:19
  • 1
    @keyboard-warrior what do you mean by "erroneous"? This is totally legal JS code. It just increments `prev[cur]`, starting with `0`. (In case, `prev[0]` is undefined, the value `0` is used instead). You could also use the expression `(prev[cur] + 1) || 1` instead, but that doesn't make much difference. – isnot2bad Oct 09 '21 at 11:16
36

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

VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    the extra if statement after the loop is unnecessary... just use `for (var i = 0; i <= array_elements.length; i++) {` or `<=` instead of `<`. – mmm Feb 09 '15 at 01:58
  • Hi @Vinay, maybe you could help me here? https://stackoverflow.com/questions/57819850/javascript-count-on-each-appearance-of-value-from-array-of-objects – SMPLYJR Sep 06 '19 at 10:05
29

Simple is better, one variable, one function :)

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);
isnot2bad
  • 24,105
  • 2
  • 29
  • 50
Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • I know this is old but it looks so simple. Can anyone explain what is happening here to a novice that has just learned the basic reduce usage. – Burton May 23 '21 at 08:32
  • 1
    Sure, reduce allows you to provide a default (second argument) value and pass it back through the reduce function so you can keep checking the new value, `acc` (accumulative) will continually update as we're cylcing through each array value, after assigning it to the object, we can check if it exists and update it's value by 1 as we're iterating through! Hope this helps :) – Shannon Hochkins May 23 '21 at 23:54
11

Single line based on reduce array function

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));
dinigo
  • 6,872
  • 4
  • 37
  • 48
  • I just realized that @isnot2bad (https://stackoverflow.com/a/32886673/621058) is almost the same as mine. I just happen to use fat arrow functions and constants – dinigo Nov 09 '17 at 11:51
11

// 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]);
Erik Martín Jordán
  • 4,332
  • 3
  • 26
  • 36
10

Nobody responding seems to be using the Map() built-in for this, which tends to be my go-to combined with 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);

N.b., you'll have to polyfill Map() if wanting to use it in older browsers.

aendra
  • 5,286
  • 3
  • 38
  • 57
  • Could you explain a little bit in-depth how this is working ? (specially the set / get part). I tried to break the reducer into a function but I have "get" is not a function in response. – Antoine Nedelec May 07 '20 at 07:32
  • Ok `get` and `set` functions are coming from the `Map` object. But the initial accumulator is not a Map object, so why does the reduced version of the reducer takes one ? – Antoine Nedelec May 07 '20 at 07:39
  • @AntoineNedelec The initial value _is_ a new `Map` object; see the second argument of the reduce. `Map.prototype.set` returns the map object, and `Map.prototype.get` returns `undefined` or the value of whatever key is supplied to it. This lets us get the current count of each letter (or `0` if undefined), then increment that by one, then set that letter's count to the new count, which returns the map and becomes the new accumulator value. – aendra May 18 '20 at 20:13
6

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                                      
5

You can solve it without using any for/while loops ou forEach.

function myCounter(inputWords) {        
    return inputWords.reduce( (countWords, word) => {
        countWords[word] = ++countWords[word] || 1;
        return countWords;
    }, {});
}

Hope it helps you!

Pablo Souza
  • 61
  • 1
  • 3
5

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 }
Julio C.
  • 55
  • 5
Yathin K Rao
  • 61
  • 1
  • 1
5
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);
pHorekka
  • 69
  • 1
  • 5
4

You can have an object that contains counts. Walk over the list and increment the count for each element:

var counts = {};

uniqueCount.forEach(function(element) {
  counts[element] = (counts[element] || 0) + 1;
});

for (var element in counts) {
  console.log(element + ' = ' + counts[element]);
} 
John Keyes
  • 5,479
  • 1
  • 29
  • 48
nkron
  • 19,086
  • 3
  • 39
  • 27
  • why did you set this condition `counts[element] || 0`? – Asking Jun 12 '20 at 12:06
  • The first time accessing `counts[element]` returns `undefined` since the property doesn't have a value yet. If you then try to add `undefined + 1`, you'll end up with [NaN](https://www.javascripture.com/Global#NaN). The `(count[element] || 0)` will replace the `undefined` with `0` so adding `1` produces `1` instead of `NaN`. ECMAScript 2020 adds the nullish coalescing operator `??` which does a similar thing but is a bit more explicit that it is using the second value when the first is `undefined` (or `null`). That version would be `(counts[element] ?? 0) + 1`. – nkron Sep 09 '20 at 06:18
4

// 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));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Ryan Luu
  • 41
  • 1
3

You can do something like that:

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;
    }
}

now you have a map with all characters count

Rami
  • 7,162
  • 1
  • 22
  • 19
3
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);
aturan23
  • 4,798
  • 4
  • 28
  • 52
2

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>");
}
2

simplified sheet.js answare

var counts = {};
var aarr=['a','b','a'];
aarr.forEach(x=>counts[x]=(counts[x] || 0)+1 );
console.log(counts)
Balaji
  • 9,657
  • 5
  • 47
  • 47
2

CODE:

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;
}

Snippet

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;
}
ARr0w
  • 1,701
  • 15
  • 31
2

Using this solution you can now get map of repeated items:

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);
timbillstrom
  • 1,176
  • 16
  • 33
Tec Mania
  • 21
  • 3
2

Steps : first check if in accumulator has the current value or not if not ,than for that particular value set the count as 1 and in else condition ,if value alreadt exist in accumulator the simple increment the count.

const testarr = [1,2,1,3,1,2,4];

var count = testarr.reduce((acc,currentval)=>{

if(acc[currentval]){ acc[currentval] = ++acc[currentval]; }else{ acc[currentval] = 1; } return acc; },{})

console.log(count);
vimuth
  • 5,064
  • 33
  • 79
  • 116
Ady
  • 67
  • 1
  • 4
1
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}`);
}
Ilya Kushlianski
  • 780
  • 9
  • 15
1

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);
1

use forEach() method for convinience

var uniqueCount="a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count=0;
var obj={};      
uniqueCount.forEach((i,j)=>{
count=0;
var now=i;
uniqueCount.forEach((i,j)=>{
if(now==uniqueCount[j]){
count++;
obj[i]=count;
}
});
});

console.log(obj);
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – abdo Salm Oct 06 '22 at 03:33
  • What is unclear in it? – Rishu Tripathi Oct 07 '22 at 04:25
0

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.

Xiaodan Mao
  • 1,648
  • 2
  • 17
  • 30
0

By using array.map we can reduce the loop, see this on 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;
}

To Test:

var test = new Check(1,2,1,4,1);
console.log(test);
Ali Adravi
  • 21,707
  • 9
  • 87
  • 85
0

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 
*/
sg28
  • 1,363
  • 9
  • 19
0

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 ] ]
Jitendra
  • 3,135
  • 2
  • 26
  • 42
0

Quickest way:

Сomputational complexity is 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']);

The shortest code:

Use 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']);
0
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;
}
thaps
  • 1
0

Declare an object arr to hold the unique set as keys. Populate arr by looping through the array once using map. If the key has not been previously found then add the key and assign a value of zero. On each iteration increment the key's value.

Given testArray:

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

solution:

var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});

JSON.stringify(arr) will output

{"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}

Object.keys(arr) will return ["a","b","c","d","e","f","g","h"]

To find the occurrences of any item e.g. b arr['b'] will output 2

jidexl21
  • 609
  • 7
  • 22
0
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,.....}
AbhiGarag
  • 1
  • 1
0

Count the Letters provided in string

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()
nano dev
  • 335
  • 4
  • 6
0

Example how to return the character that is most commonly used in the string.

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'))
-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");

}   

}