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

108
Visualizações
I would like to count matching neighboring items in an array and return the count

I have an array and i would like to find all neighboring matches and count them, then return the count, performed in a loop like .map() so it wont be necessary to store a memory of what was counted beyond the current element. i need to use this number of current elements to reserve enough spaces for each group of elements

array = [ball, batter, batter, amount, amount, github, github, github, account, account, account, account, account, account, account, github, github, github]

example of desired results from this array would be: on first loop would return 1, second loop would return 2, then 2, then 3, then 7, then 3

and this count would be used as a variable to reserve space, something like

number to reserve: count

so through each loop, the variable count would be changed and updated to the current elements count, and the loop that counts would not stop until the next element is not a match for the current element, and the variable count will also not be available for use until all concurrent matches are found, so if i put console.log(count) at the end of the function i would get each number output individually

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

0

You can easily count the consecutive string in an array as:

const array = ["ball", "batter", "batter", "amount", "amount", "github", "github", "github", "account", "account", "account", "account", "account", "account", "account", "github", "github", "github"]

const result = [];
let last = array[0], lastSameIndex = 0;
for (let i = 1; i < array.length; ++i) {
  if (array[i] !== last) {
    result.push(i - lastSameIndex);
    lastSameIndex = i;
    last = array[i];
  }
}
result.push(array.length - lastSameIndex);

console.log(result);


Let's declare some initial values as

last = array[0], so last = "ball", and lastSameIndex = 0

So we have to start from the index 1 and we only have to consider a single case where the two elements are not equal i.e. array[i] !== last. If they are not equal then we have to push the count of same element till now as:

result.push(i - lastSameIndex);

Now, we have to update the new value and index i.e. last element from where we have to count that element again.

lastSameIndex = i;
last = array[i];

So far so good, but we also have to handle a case where the loop ends, In this case we have to push the count of last element from where the count started i.e. last started or lastSameIndex till the last element.

result.push(array.length - lastSameIndex);

Second solution

const array = [ "ball", "batter", "batter", "amount", "amount", "github", "github", "github", "account", "account", "account", "account", "account", "account", "account", "github", "github", "github"];

let lastStr = "",
  num = 0;
const result = array
  .map((s) => {
    if (lastStr !== s) {
      lastStr = s;
      num = num === 0 ? 1 : 0;
    }
    return num;
  })
  .join("")
  .match(/(\d)\1*/g)
  .map((s) => s.length);
  
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

So loop each item, if it's not equal to the last item, push 1, else add 1 to the last number in the array.

const items = ["ball", "batter", "batter", "amount", "amount", "github", "github", "github", "account", "account", "account", "account", "account", "account", "account", "github", "github", "github"]

const results = [];

items.forEach((item, i) => {
    if (items[i - 1] !== item) return results.push(1);

    const last = results.length - 1;
    results[last] = results[last] + 1;
});

console.log(results);

about 4 years ago · Juan Pablo Isaza Relatório

0

  • Try to join the array into string seperated with comma by array.join(","): ball,batter,batter,amount,amount,github,github,github
  • Use regex: /([a-z]+,)\1*/gi to match same repeated word Gives: ['ball,', 'batter,batter,', 'amount,amount,', 'github,github,github,...]
  • Count how many word in each string of array by using s.split(',').length-1

Script:

array.join(",").match(/([a-z]+,)\1*/gi).map((s) => `${s.split(',').length-1}`);

Result: ['1', '2', '2', '3', '7', '2']

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