Using JavaScript to tally frequency of array values

I am working with a JavaScript array that has a length of 129.

var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]

My goal is to determine how many times each name appears in the array and store that information in another array like this:

var counter = [2, 5, 7, ..]

For example, if Karri appeared in the fullnames array 2 times, Ismo appeared 5 times, and so on. Does anyone have any suggestions on how to achieve this?

Answer №1

This method is both efficient and straightforward:

var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};

for (var i = 0; i < fullnames.length; i++)
{
    if (!counts.hasOwnProperty(fullnames[i]))
    {
        counts[fullnames[i]] = 1;
    }
    else 
    {
        counts[fullnames[i]]++;
    }
}

console.log(counts);

Link to Original Fiddle.

Opting for an object instead of an array for storing the counts proves to be a more logical choice in this case.

Answer №2

Assuming fullnames is an array of strings, here is a way to count occurrences:

var nameCounts = { };
for (var i = 0; i < fullnames.length; i++) {
    if (typeof nameCounts[fullnames[i]] == "undefined") {
        nameCounts[fullnames[i]] = 1;
    } else {
        nameCounts[fullnames[i]]++;
    }
}

console.log(nameCounts); // Outputs something like: {"John": 2, "Alice": 5, ...}

Answer №3

let people = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
let counts = [];
people.forEach(function(_person) {
    if(typeof counts[_person] === 'undefined') counts[_person] = 1;
    else counts[_person]++;
});
let result = [];
for(i in counts) result.push(counts[i]);
console.log(result);

// shows [3, 3, 5]

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 callbacks from using Mongoose findById() only yield results for irrelevant information

I am currently using Mongoose for database operations. I am experiencing an issue where the findById() method is sometimes returning results, but not consistently: Case 1: Invalid Query models.Repo.findById("somefakeid", function(err, result){console.log ...

Exploring Alternative Methods to Navigate Through Elements Using JQuery UI Autocomplete

After testing two different approaches: <div id = "team-search-container"> <label for="team-search" class = "text-center"> <input type = "text" id = "team-search"> </label> </div> With the following code sni ...

Guide on adjusting the CSS styling of elements in real-time from the backend using a user customization panel to modify the appearance of various web pages

Imagine a scenario where we have a website consisting of multiple pages, including a user account page. The user has the ability to modify the color, font size, and style of certain elements on other pages for their own viewing preferences. How can this fu ...

importing files from Uploadcare using ngCordova MediaFile

I am facing an issue while attempting to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The `uploadcare.fileFrom('object')` function is failing with an 'upload' error even though I have set the public k ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

Removing the last two characters from a number with a forward slash in Vue.js

I'm encountering a slight issue with my code: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the item.id numbers (Example: 002917/1) contain ...

Error: The variable success_msg has not been defined in the EJS Reference

I am in the process of developing a library website for my school that includes login and administration capabilities. I am relatively new to node.js and EJS, but I recently revamped the routing and page delivery system to use EJS and express. As part of u ...

Integrate Vue Login Functionality using Axios HTTP Requests

Hello everyone! I am new to Vue and currently struggling with making an HTTP Request to my backend. When I check the browser console, I can see the access token retrieved from /login endpoint but when I try to fetch data from api/users, it returns "Token ...

How can TypeORM be used to query a ManyToMany relationship with a string array input in order to locate entities in which all specified strings must be present in the related entity's column?

In my application, I have a User entity that is related to a Profile entity in a OneToOne relationship, and the Profile entity has a ManyToMany relationship with a Category entity. // user.entity.ts @Entity() export class User { @PrimaryGeneratedColumn( ...

Passing data between pages using React Native hooks

I am a newcomer to React Native and facing challenges in passing data to another page. Specifically, I want to transmit data from the QR Reader to another Page. Below is my code on the first screen: const LoginScreen = (props) => { const onSucce ...

Navigating through a 3D world with just the tilt of

I am currently developing an immersive VR web application using three.js. I have integrated the device orientation controls from the Google Cardboard three.js demo for camera navigation. Now, I am looking to incorporate keyboard controls for additional fu ...

The Angular binding for loading does not correctly reflect changes in the HTML

Whenever a user clicks the save button, I want to display a loading indicator. The state changes correctly when the button is clicked, but for some reason, reverting back the value of the loading property on scope to false doesn't update the UI. Coul ...

Are the keys in Postgresql JSON displayed with underscores separating the letters?

I'm currently developing a web application that communicates with a Rails API on top of a Postgres database. As part of my data storage strategy, I am utilizing the jsonb datatype in Postgres to store certain data in JSON format. To adhere to a consis ...

Can the minimum length be automatically filled between two elements?

I'm struggling to find a way to adjust the spacing of the "auto filling in" dots to ensure a minimum length. Sometimes, on smaller screens, there are only one or two dots visible between items. Is there a way to set a minimum length for the dots in th ...

Utilizing arrays in PostgreSQL dynamic SQL parameters

In my attempt to execute a dynamic query, I came up with the following approach: declare params text[] ; begin params := ARRAY['30', 'sometext']; return execute QUERY 'select id, label from "content" wher ...

Is there a method to merge elements from two separate "lists of lists" that contain the same elements but have different lengths within each list?

In an attempt to merge two distinct lists of lists based on shared elements, I find myself faced with a challenge. Consider the following: list1 = [['a1', 'a2', 'b2'], ['h1', 'h2'], ['c1', ' ...

The correlation between frames per second (FPS) and the milliseconds required to render a frame in the stats plugin is known as the frame

Recently, I've implemented the Stats.js plugin to keep track of my three.js performance. Something seems off with the FPS (frames rendered per second) and MS (milliseconds needed to render a frame) information: According to my calculations, if it ta ...

Adjust the sequence of the series in dimple's multi-series chart using interactive features

My latest project involves a unique dimple interactive chart featuring two series: a pie series and a line series based on the same dataset. You can view the chart at dimplejs.org/advanced_examples_viewer.html?id=advanced_interactive_legends Check out the ...

I'm curious, is there a maximum limit for numeric array keys in PHP

I've encountered an issue with arrays in PHP where the keys are being unexpectedly changed. In the example below, I start with a string but somehow it's getting converted to an integer and altering the key when added to another array. Code ----- ...

React Native: Why is useState setter not causing a re-render?

As a beginner in react and javascript, I am facing an issue with showing an ActivityIndicator while logging in a user. The setIsLoading method doesn't seem to change the state and trigger a rerender. When the handleLogin method is called on a button c ...