Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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
  ]
]
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda