In this case it is best to use reduce()
on the array. Essentially your starting with an empty object and then you start iterating over the elements in your array. If the value you encounter is unknown, add the value as a property to the object as set its value i.e. its number of occurrences to 1. If you encounter a value that is already know, it must already be in the object, then get that count and increase it by one.
At the end of the loop you will have a count for each value in the array. This algorithm has a runtime complexity of O(n)
which is an asymptotically optimal algorithm as the lookup in the object happens in O(1)
. You could also implement this with a Map
, which would essentially be the same algorithm (see below).
You can think of the Map/ JS object as your different count variables rank1
, rank2
, rank3
, .... Only difference is, it scales to however many count variables you need and you pick variable which you need to increase automatically by simply using the value that you want to count.
with JS object
const array1 = ["Rank1", "Rank1", "Rank1", "Rank3", "Rank2", "Rank4", "Rank1", "Rank3"];
const count = array1.reduce((prev, cur) => {
if(prev.hasOwnProperty(cur)) prev[cur]++;
else prev[cur] = 1;
return prev;
}, {});
console.log(count);
Expected output:
{ Rank1: 4, Rank3: 2, Rank2: 1, Rank4: 1 }
with Map
const array1 = ["Rank1", "Rank1", "Rank1", "Rank3", "Rank2", "Rank4", "Rank1", "Rank3"];
const count = array1.reduce((prev, cur) => {
if(prev.has(cur)){
let currentCount = prev.get(cur);
currentCount++;
prev.set(cur, currentCount);
}
else prev.set(cur, 1);
return prev;
}, new Map());
console.log([...count.entries()]);
Expected output
[
[
"Rank1",
4
],
[
"Rank3",
2
],
[
"Rank2",
1
],
[
"Rank4",
1
]
]