I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me.

I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total in the "diary" array.

Here's the code in question

Can someone point out what I might be doing incorrectly? Appreciate it. :)

Answer №1

Instead of using the includes method which only returns a boolean, you can achieve the desired result by utilizing the filter method.

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: Implementing reduce and 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);

Answer №2

Apologies for my previous response, I have now reviewed the code and this is the correct version:

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[i].length;j++) {
    const entries = journal[i][j];
     if(entries.includes(event)){
      number++;
     }
    }
   
  }

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

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

Answer №3

The reason why it only returns two is because the includes() method does not count occurrences, but rather returns a boolean value. Your code only counts how many times the true statement occurs. In this case, since the array length is 2 and every element happens to have 'Home', your code only returns 2.

There are multiple ways to achieve what you want, but what I did below is use multiple forEach loops (or you can use a for loop as well) to iterate through a multidimensional 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)

*Apologies if my English is not perfect.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to stop form submission in AngularJS when submitting the form by pressing the enter key?

I have implemented validation on my form (which consists of only two fields) but I am struggling to figure out how to prevent it from being submitted with empty data. The current flow is as follows: Upon pressing the enter key, the student's name and ...

Looping through a JSON array

Currently, I am working with asp.net in Visual Studio and using jQuery to call a web method. In asp.net, I am generating a dynamic datatable and then returning it by using JsonConvert.SerializeObject(dt). $.ajax({ type: 'POST', url: &apo ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

Can JQuery be used to identify the CSS styles applied to selected elements?

Highlight the text by selecting it and clicking a button. If the text is already highlighted, clicking the button should make the selected text return to normal. Can this be achieved using jQuery and a single button? Is it possible to identify the CSS st ...

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Unable to deserialize an instance of java.util.List from the VALUE_STRING

In the process of developing a new application, my goal is to send data to a server and receive a response in a specific format. Here's an example of how the format should look: { "userName" :"<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Maintain consistent theme across various pages using javascript

So I successfully implemented a dark mode on the front page using the following script (sourced from W3schools) : <script> function darklightmode() { var element = document.body; element.classList.toggle("dmode"); } </script> ...

Combining the power of Kendo UI with the flexibility of Vue

Hey there everyone, I'm currently utilizing the Vue.js CLI for my project. Recently, I came across a helpful tutorial on incorporating a Jquery plugin into a webpack project at this link: . To achieve this, I installed the expose loader and added th ...

Add elements continuously without the need to refresh the page

How can I dynamically create a variable value by combining two different inputs without having to reload the page Here is the code snippet: {exp:safecracker channel="blending_log" return="sthome/blending/ENTRY_ID"} <h3>Select and enter data</h3 ...

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

Can you explain the different types of dynamic page props available in a Next.js application?

Is there a specific type available in Next.js 14 that I can use to replace the "any" type in the TypeScript code snippet below, for my dynamic route? export default async function DetailProduct({ params }: any) { const { imageAddress, title, price } = ...

Tips for creating a custom script in my React Native application

My React Native app requires a script to generate static files during the release process. The app is a game that utilizes pre-computed boards, which are resource-intensive to compute. Therefore, I am developing a script that will create these boards and s ...

Launching PDF on IE11 in a new tab seamlessly without any prompts - mssaveoropenblob

We are in the process of transitioning an ASP.NET MVC application that used to have the functionality of opening a PDF file in a new tab using FileContentResult. return new FileContentResult(byteArray, "application/pdf"); As part of this migration to Rea ...

Tips on implementing a Javascript function triggered by a user's click within the video player frame

<script> function greet() { alert("hello"); } </script> <iframe width="100%" height="315" src="https://www.youtube.com/embed/AGM0ibP1MRc" onclick="greet()"></iframe> .Kindly assist me, please. ...

What is the method to render certain text as bold using a json string?

I need assistance with concatenating two strings in react while ensuring that the first string is displayed in bold, while the second one remains unchanged. The first string I want to emphasize is stored in a JSON file, and the second string comes from an ...

The initiation of jQuery animation through user interaction hinges on the completion of the preceding animation

In my project, I've designed a timeline that offers users the ability to zoom in and out by simply clicking on corresponding buttons. Since the timeline is too large to fit entirely on the screen, it is contained within a scrollable div. To ensure tha ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...

How to access a variable from within a Phonegap DB function and return it outside of the

I'm struggling with a phonegap db JavaScript script that isn't returning the final string variable "feeds" outside the function. It's currently showing as "undefined". I need help making the necessary changes to properly return the "feeds" v ...