Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For-each in a array Javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try the following below code.

var rank1 = 0
var rank2 = 0
var rank3 = 0
var rank4 = 0

const array1 = ['rank1','rank1','rank1','rank3']

array1.forEach( function( item, i ) {
  
  eval( item + '+= ' + 1 + ';');
  
} );

console.log(rank1, rank3);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading