"Utilizing an if-else statement within a forEach loop

I have an array of ages and I want to determine the age range for each age along with the count, then push it into my object.

The issue I am facing is that if there are multiple ages in the same range, it gets pushed twice. I only want to push it once and display the length, but it returns undefined.

Here is the code on StackBlitz

this.ages = [18, 20, 1];

this.ages.forEach((age) => {
  // Infant
  if (age >= 0 && age <= 1) {
    this.id = 1;
    this.travel.listOfTravellerCountPerAgeRange.push({
      travellerAgeRangeId: this.id,
      travellerCount: age.length,
    });
  }

  // Adult
  else if (age >= 12 && age <= 59) {
    this.id = 3;
    this.travel.listOfTravellerCountPerAgeRange.push({
      travellerAgeRangeId: this.id,
      travellerCount: age.length,
    });
  }
});
console.log(this.travel);

The output displayed from console.log is:

listOfTravellerCountPerAgeRange: [  
{travellerAgeRangeId: 3, travellerCount: undefined},
{travellerAgeRangeId: 3, travellerCount: undefined},  
{travellerAgeRangeId: 1, travellerCount: undefined} ]

The desired output I hope to achieve is:

 listOfTravellerCountPerAgeRange: [  
 {travellerAgeRangeId: 3, travellerCount: 2}, 
 {travellerAgeRangeId: 1, travellerCount: 1} ]

Answer №1

To calculate a specific value from an array of items, consider utilizing the reduce method:

this.trip = {};
this.people = [1,1,45];

this.trip.countOfTravelersPerAgeRange = this.people.reduce((acc, p) => {
  let id
  if (p >= 0 && p <= 1) {
    id = 1;
  } else if (p >= 12 && p <= 59) {
    id = 3;
  }
  const result = acc.find((entry) => entry.ageRangeId === id);
  if (result) {
     result.travelerCount += 1;
  } else {
    acc.push({ageRangeId: id, travelerCount: 1});
  }
  return acc;
}, []);

console.log(this.trip.countOfTravelersPerAgeRange);

I haven't executed this code, but it should be functional =)

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

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...

Utilizing JavaScript and JSON to Retrieve Array Elements by Key Names as Indexes

I'm looking for a way to access elements in an array using unique key names instead of numerical indexes. Specifically, I'm developing a Discord bot where each server has its own settings. When a message is sent on a server, I need to retrieve th ...

An introduction to utilizing .keypress() in jquery

I'm exploring the use of .keypress() to allow users to press enter and trigger a button click on my modal (which closes the modal). When I initially code it as: $(document).keypress(function () { console.log('keypress'); }); it works, but ...

PHP/MySQL clarification regarding time slots

Could someone assist me with this discussion I found? Due to my low reputation, I am unable to comment for further clarification. Although I grasp the solution provided in the mentioned discussion, I am struggling to comprehend how to pass the data to my ...

Default Value for Null in Angular DataTable DTColumnBuilder

What is the best way to define a default value in case of null? $scope.dtOptions = DTOptionsBuilder .fromSource('api/Restt/List'); $scope.dtColumns = [ DTColumnBuilder.newColumn('modi ...

The CORS Policy error message "The 'Access-Control-Allow-Origin' header is missing on the requested resource" in Next.js

Encountered an issue with CORS Policy error while attempting to redirect to a different domain outside of the project. For example, trying to navigate to https://www.google.com through a button click or before certain pages load. The redirection was handl ...

What are the necessary conditions for executing npm start?

I'm encountering issues running npm start in my project, which is linked to my package.json file below: { "name": "babek", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test speci ...

Preventing bots and spiders from infiltrating the ad network. Stepping up efforts to block unwanted traffic

We are facing a constant battle against bots and spiders with our in-house ad system, striving for 100% valid impressions. To achieve this goal, I conduct experiments on a specific ad zone that is only displayed on one page of our site. By comparing the G ...

Utilize an image in place of text (script type="text/javascript")

The vendor has provided me with some code: <a class="sh_lead_button" href="https://107617.17hats.com/p#/lcf/sfrnrskrvhcncwvnrtwwvhxvzkrvzhsd" onclick="shLeadFormPopup.openForm(event)">FREE Puppies</a> <script type="text/javascript" src="htt ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

What is the best way to keep the textfield value at 0? If you clear the textfield, it will result in another value being

If I don't input anything in this field, the total will show as isNaN, and I want to prevent form submission if it is isNaN. How can I stop the form from being submitted when the total value is isNaN? export default function BasicTextFields() { cons ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

Attaching a function to a designated slot attribute

Currently, I am utilizing VUE 2.6.11 along with class components. My current objective involves encapsulating components that can serve as modals inside a separate component responsible for managing the modal state. According to the documentation, it is p ...

A Guide to Effortlessly Implementing moment.js into a React TypeScript Application

I'm attempting to implement code splitting and one of the specific packages I want to separate into its own chunk is moment.js. Here's how I'm doing it: const myFunc = async (currentNumber) => { const moment = (await import('momen ...

React - Ensure useEffect is triggered only after state update

One of my components (ItemsIndex) is using a custom hook to fetch data from our API. However, the ItemsIndex's useEffect runs first, causing the DOM to not be filled with elements that could be scrolled into view. How can I make sure that the useItems ...

What is the most effective way to compare two arrays of objects in JavaScript?

I'm working on a function that needs to return an array of elements based on certain filters. Here is the code for the function: filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) { let tempFilterArray = []; ...

Show additional information when a row in the Bootstrap Vue table is clicked

I am attempting to create a unique user experience by displaying row details when a row is clicked, rather than clicking on a button as described in the documentation. However, the documentation lacks specific instructions on how to implement this feature. ...

Mismatched URLSearchParam type {property: value} does not match with undefined and Argument Type {property: value} cannot be assigned to {property: value}

Every time I try to run the code below, I encounter this error. The code is supposed to take a refresh token as input and make a POST request using URLSearchParams to a specific URL. However, I keep getting an error related to URLSearchParams. https://i.s ...

Ways to display certain JSON elements

I'm attempting to retrieve a specific part of a JSON file through AJAX and display it in an HTML div. I only want to show a certain object, like the temperature. Here is the AJAX code: $(function () { $.ajax({ 'url': 'http://ap ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...