Determining the age range using JavaScript

Struggling lately to tally the duplicate elements in an array and convert them into objects. Currently, I am attempting to calculate the frequencies of age ranges. Here is a code snippet that counts duplicate ages:

const age = [5, 5, 16, 5, 16];

const sumAge = {};
for (const datum of age) {
    let entry = sumAge[datum];
    if (entry) {
        ++entry.count;
    } else {
        sumAge[datum] = {age: datum, count: 1};
    }
}

console.log(Object.values(sumAge));

This results in

{
   age:5,
   value: 3
},
{
   age:16,
   value: 2
}

Currently tackling the task of achieving this expected outcome

{
   age:5-15,
   value: 3
},
{
   age:16-30,
   value: 2
}

Answer №1

By defining the age brackets, the process becomes more simplified. Utilize the find method to identify the appropriate age bracket and use it as a key. You can also consider using Other for cases where the age does not fall within any of the specified ranges.

const ages = [5, 5, 16, 5, 16,99];
const ageRanges = {
   "5-15":{ min:5, max:15},
   "16-30":{ min:16, max:30},
}

const summaryOfAges = {};
for (const data of ages) {
   var selectedRange = Object.keys(ageRanges).find(r => ageRanges[r].min<=data && ageRanges[r].max>= data) || "Other";
    let currentEntry = summaryOfAges[selectedRange];
    if (currentEntry) {
        ++currentEntry.count;
    } else {
        summaryOfAges[selectedRange] = {age: selectedRange, count: 1};
    }
}

console.log(Object.values(summaryOfAges));

Answer №2

This is my preferred method

const age = [5, 5, 16, 5, 16];
// Defining age ranges with Infinity included
const ranges = {
    '0-4': {low: 0, hi:4, value:0},
    '5-15': {low: 5, hi:15, value:0},
    '16-30': {low: 16, hi:30, value:0},
    '30+': {low: 31, hi:Infinity, value:0}
};
const rangeArray = Object.values(ranges);
for (const datum of age) {
    rangeArray.find(range => range.low <= datum && datum <= range.hi).value++;
}
const sumAge = Object.entries(ranges).filter(([_, {value}]) => value).map(([age, {value}]) => ({age, value}));

//
console.log(JSON.stringify(sumAge, null, 4));

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

Contrasting the impact of opening your HTML files from the desktop versus running a development local server for your files

As I delve into web design, I've noticed a trend on YouTube where creators utilize virtual servers to upload and preview their code. This got me thinking - what advantage does using a local server offer compared to simply opening the HTML file in my b ...

What is the meaning of this CSS acronym?

div[id^=picture]:target{ /*applying various styles here*/ } I stumbled upon the snippet of code shown above on a website discussing CSS image galleries. Can anyone clarify what this code accomplishes? Appreciate it. ...

How can I trace the origin of a post request sent from a form?

When constructing an HTML form, I typically utilize <form action="/postRoute" method="post"> to submit a post request. However, while examining a form for which I needed the post request URL, I came across the following: <form action="index.cf ...

Solving Mixed Content Issues in JavaScript

I'm attempting to retrieve information from OMDB API, but I'm encountering an issue with mixed content images. OMDB pulls its data from IMDB, which does not allow the use of https images. Therefore, all image sources must be prefixed with http. ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

"Converting a text into a property that can be

In my scenario, I have a set of fixed options along with a dynamic number of yes/no radio inputs named other[index]. By utilizing $(form).serializeArray(), I can obtain an array of name/value objects. Through the use of the reduce method, I am then able to ...

What is the best approach to integrate express.js with truffle contracts?

While following a tutorial on Youtube about creating a decentralized voting app on truffle, I encountered a situation where I wanted to include a login and sign up feature into the system. Since lite-server couldn't send Mysql queries like express.js ...

Insert discover within the tube

Can I modify the following code to add a pipe before the subscribe method that performs the find operation, so that only one panel is returned by the subscription? await this.panelService.getActivePanels() .pipe( map(activePanels => active ...

I am encountering issues with my JavaScript files that appear to be following the correct path, however they are not functioning properly. Error messages such as SyntaxError: expected expression

I am currently working on a Yii2 application. My goal is to utilize the JavaScript and CSS files from the common folder in my backend. The paths for these files are within the common/web/js and common/web/css directories respectively. To achieve this, I ...

Issue with monitoring server responses with Angular $http service in Node.js controller

After creating a form, I want to display the server response (nosejs) upon clicking submit. The response is visible when called from the service directly, but nothing appears when called from the controller. Controller: MyApp.angular.control ...

Functionality of the Parameters Object

As I transition from using the params hash in Rails to learning Node/Express, I find myself confused about how it all works. The Express.js documentation provides some insight: 'This property is an array containing properties mapped to the named rout ...

Unable to connect HTML data to the view section using angular.js

I am trying to incorporate some HTML content into my view using angular.js. time.html: <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align="center">Time <i class="fa fa-long- ...

Performing an Ajax request to the server and then sending the retrieved data back to Charts.js

After extensively researching ajax, php, and related topics, I'm facing a challenge. I want to take an array retrieved from my database and integrate it into a chart.js script. The data retrieval seems fine as per Firebug inspection, but the issue ari ...

Is there a way to link to mouseover and mouseleave actions while utilizing ng-options?

I am trying to create a directive that will handle the mouseover and mouseleave events for the option elements within this select element: <select class="form-control" custom-directive="" ng-model="vm.selectedPersonalInfo" ng-options="personalInfo as p ...

The functionality to import JSON data into Google Spreadsheets is compromised when the API includes the characters " | "

I am attempting to bring JSON data into Google Sheets using a Wikidata API. However, one of the symbols utilized in this API is the vertical bar: |. It serves as an "and". For instance, if I wish to import data in BOTH English and Greek, then I need to us ...

Appending a secondary column containing duplicated elements from the initial column

I am currently working with a 2D array that has 6 rows and 2 columns. My goal is to calculate the sum of values in the second column based on the values in the first column. However, I am unsure of how to proceed in transferring these calculated values to ...

Creating a series of values to populate a column in a data frame

Imagine having a data set called "Address" structured like this: Street HouseNumber A Fakestreet1 10 bla Fakestreet2 20 bla Fakestreet3 30 bla Fakestreet4 40 bla You want to introduce a new ...

Capturing and saving detailed hand-drawn artwork in high resolution

Is there a cutting-edge solution available for capturing hand-drawn sketches (from a tablet, touch screen, or iPad-like device) on a website using JavaScript and saving it on the server side? Essentially, I am looking for a mouse drawing canvas with a hig ...

Exploring Date Comparisons in AngularJS

Currently, I am in the process of developing a web application using AngularJS and Rails. One of the features involves creating bookings through a bookings function. In the dashboard section of the app, I aim to have two tabs - one for Current Bookings and ...

Angular 2 404 Error persists despite successful retrieval of data from Oracle database using Backend Nodejs URL entered directly into the browser

Recently, I've been working on displaying data in my Angular frontend that is fetched from an Oracle DB connected to my Node backend. When I access the physical API link, the data appears and is displayed in the backend console.log. I'm wonderin ...