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

152
Visualizações
Looping through array of objects is only returning one object of elements instead of two. What am I doing wrong?

Forewarning I am new to coding so be patient with me.

I'm trying to loop through the "diary" array & the function "howMany" is only returning 2 'Home' elements, when there are 4 elements of 'Home' overall in the "diary" array.

Code in question

What am I doing wrong? Thank you. :)

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

0

You're using the includes method which only returns the boolean. If it's matched, even got 4 matches, the number only will be increased by 1 for each loop.

This is another way to achieve that by using filter.

let diary = [];

const addEntry = (events) => {
  diary.push({ events });
};

addEntry(['Home', 'Work', 'Park', 'Beach', 'Home']);
addEntry(['Work', 'Home', 'Store', 'Gas Station', 'Home']);

const howMany = (event, journal) => {
  let number = 0;

  for (let i = 0; i < journal.length; i++) {
    let entry = journal[i];
    number += entry.events.filter((e) => e === event).length;
  }

  console.log(`You did that ${number} time(s)`);
};

howMany('Home', diary);
console.log(diary);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


Update: Using reduce & filter.

let diary = [];

const addEntry = (events) => {
  diary.push({ events });
};

addEntry(['Home', 'Work', 'Park', 'Beach', 'Home']);
addEntry(['Work', 'Home', 'Store', 'Gas Station', 'Home']);

const howMany = (event, journal) =>
  journal.reduce(
    (acc, curr) => acc + curr.events.filter((e) => e === event).length,
    0
  );

const number = howMany('Home', diary);

console.log(`You did that ${number} time(s)`);    
console.log(diary);
about 4 years ago · Juan Pablo Isaza Relatório

0

sorry for earlier answer i didnt review the code this is the correct one

let diary = [];

const addEntry = (event) => {
  diary.push(event);
};

addEntry(['Home', 'Work', 'Park', 'Beach', 'Home']);
addEntry(['Work', 'Home', 'Store', 'Gas Station', 'Home']);

const howMany = (event, journal) => {
  let number = 0;

  for (let i = 0; i < journal.length; i++) {
    for(let j =0;j < journal.length;j++) {
    const entries = journal[i][j]
     if(event.includes(event)){
      number++
     }
    }
   
  }

  console.log(`You did that ${number} time(s)`);
};

howMany('Home', diary);
console.log(diary);

about 4 years ago · Juan Pablo Isaza Relatório

0

The reason why it returning only two is because includes() method will not count on how many occurrence of it occur, but only return boolean. And your code only count how many true statement is occur. In your case, because the array length is 2 and every element happens to have 'Home', your code only returning 2.

There are multiple way to achieve what you want but what I do below is to use multiple foreach (or you can use for loop as well) kinda like checking 2d array.

let diary = []

const addEntry = events =>{
    diary.push({events})
}

addEntry(['Home', 'Work', 'Park', 'Beach', 'Home'])
addEntry(['Work', 'Home', 'Store', 'Gas Station', 'Home'])

const howMany = (event, journal) => {
    let number = 0;
  journal.forEach(element => {
    element.events.forEach(item => {
      if (item === event) {
        number++
      }
    })
  });
  console.log(`You did that ${number} time(s)`);
}

howMany('Home', diary)
console.log(diary)

*sorry if my english is pretty bad.

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