var rank1 = 0
var rank2 = 0
var rank3 = 0
var rank4 = 0
const array1 = [Rank1, Rank1, Rank1, Rank3]
var Rank1 = Rank1
var Rank2 = Rank2
var Rank3 = Rank3
var Rank4 = Rank4
array1.forEach((Rank1) => {
rank1
});
array1.forEach((Rank2) => {
rank2
});
array1.forEach((Rank3) => {
rank3
});
array1.forEach((Rank4) => {
rank4
});
I'm trying to loop through array1
and save the number of times each item occurred in the array to their var.
For example, if array contains two Rank1, I want the variable rank1 to be equal to 2.
if i console.log rank1, rank2, rank3, rank4 i get the result 4,4,4,4 instead of the wanted result that would be 3,0,1,0 in this case
CodePudding user response:
In this case it is best to use reduce()
on the array. Essentially your starting with an empty object and then you start iteration 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.
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);