Extracting object properties and tallying their occurrences

How can I extract a single property from an array of objects like the following:

[{"name":"Bryan","id":016, "counter":0}, {"name":"John","id":04, "counter":2}, {"name":"Alicia","id":07, "counter":6}, {"name":"Jenny","id":015, "counter":9}, {"name":"Bryan","id":016, "counter":0}, {"name":"Jenny","id":015, "counter":9}, {"name":"John","id":04, "counter":2}, {"name":"Jenny"    ,"id":015, "counter":9}];

I want to extract the name property from each object and then count the number of occurrences of each name to create the following structure:

[{"name":"Bryan","Number":2},
{"name":"John","Number":2},
{"name":"Alicia","Number":1},
{"name":"Jenny","Number":3}]

Answer №1

Are you interested in disregarding the existing id and counter props?

One approach could be to create an object to maintain unique names and then convert it back to an array:

var data = [{"name": "Bryan",  "id": 016,  "counter": 0}, {  "name": "John",  "id": 04,  "counter": 2}, {  "name": "Alicia",  "id": 07,  "counter": 6}, {  "name": "Jenny",  "id": 015,  "counter": 9}, {  "name": "Bryan",  "id": 016,  "counter ": 0}, {  "name": "Jenny",  "id": 015,  "counter ": 9}, {  "name": "John",  "id": 04,  "counter": 2}, {  "name": "Jenny",  "id": 015,  "counter": 9}];

var result = data.reduce(function(result, item) {
  if (!result[item.name]) {
    result[item.name] = {
      name: item.name,
      counter: 0
    };
  }

  result[item.name].counter += 1;
  
  return result;
}, {});

console.log(Object.keys(result).map(function(key) { return result[key] }));

Answer №2

To keep track of the number of occurrences of each name, a hash table can be utilized as a reference.

var data = [{ name: "Bryan", id: "016", count: 0 }, { name: "John", id: "04", count: 2 }, { name: "Alicia", id: "07", count: 6 }, { name: "Jenny", id: "015", count: 9 }, { name: "Bryan", id: "016", count: 0 }, { name: "Jenny", id: "015", count: 9 }, { name: "John", id: "04", count: 2 }, { name: "Jenny", id: "015", count: 9 }], grouped = [];

data.forEach(function (item) {
    if (!this[item.name]) {
        this[item.name] = { name: item.name, occurrences: 0 };
        grouped.push(this[item.name]);
    }
    this[item.name].occurrences++;
}, Object.create(null));

console.log(grouped);

Answer №3

Let's give this a go. We start by creating a dictionary called nameDict to store names and their respective counts. Next, we iterate through a list of names to tally them up.

var arr = [{"name":"Bryan","id":"016", "counter":0}, {"name":"John","id":"04", "counter":2}, {"name":"Alicia","id":"07", "counter":6}, {"name":"Jenny","id":"015", "counter":9}, {"name":"Bryan","id":"016", "counter":0}, {"name":"Jenny","id":"015", "counter":9}, {"name":"John","id":"04", "counter":2}, {"name":"Jenny","id":"015", "counter":9}];
var nameDict = {};

for(var i = 0; i < arr.length; i++)
{
    var name = arr[i].name;
    if(nameDict[name] == undefined){
        //if the name is not in the dictionary, add it with a count of 1
        nameDict[name] = 1
    } else {
        //if the name is already in the dictionary, increment the count
        nameDict[name] += 1
    }
}

console.log(JSON.stringify(nameDict));

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

Using Python to generate a JSON file containing a list of artifacts through a loop

My file_list variable contains a list of files (artifacts), although it has been shortened for this example. print(type(file_list)) <class 'list'> print(file_list) ['file_AA.txt', 'file_BB.txt', 'file_CC.txt', ...

Adding a property conditionally in jsx: A guide

I have a simple example of Material UI RadioGroup code that I want to display conditionally in either a row or column format. By default, it is displayed in column format. Below is the code snippet: <RadioGroup aria-label="gender" name=&q ...

Sending Data from Browser to Node.js using Ajax

I've been struggling to send an AJAX post request to my Node server built with Express for a while now. Despite reading various solutions on similar issues, I couldn't figure out which files to edit. Initially, I attempted using `http.createServe ...

I'm having trouble sending a string to a WCF service using jQuery AJAX. What's preventing me from sending strings of numbers?

Something strange is happening with my web service when using jquery ajax - I can only pass strings containing numbers. This was never an issue before as I would always just pass IDs to my wcf service. But now that I'm trying something more complex, I ...

Encountering issues with proper function of history.listen within React Router

I am struggling to get my function to work every time React detects a change in the URL. The history.listen method is not triggering (the console.log statement is not showing up). I have read that this issue may be related to using BrowserRouter, but when ...

Allocate Memory for a 2D Array

I am trying to create a two-dimensional array using the following code: int * own; own = (int *)calloc(mem_size, sizeof(int)); for (i=0;i<mem_size;i++){ own[i] = (int *)calloc(3, sizeof(int)); } But when I try to access own[i][j], I encounter an ...

The percentage height setting for a div is not functioning properly, but setting the height in pixels or viewport

Within a dialog box body, I am attempting to display a table and have applied a CSS class to the wrapping div. When specifying the height in pixels or viewport height units, it works as expected. However, when using a percentage like 50%, the height of the ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

Making an Ajax call using slash-separated parameters

Handling APIs that require slash-separated parameters in the URL can be quite tricky. Take for example: http://example.com/api/get_nearest_places/:en_type_id/:longitude/:latitude One way to build this URL is by concatenating strings like so: var longitu ...

Utilize the search bar within a JavaScript function

One issue I am facing is taking an input from a search box and using that value as a parameter for another function. However, every time I click the button, the global variable resets itself when the page refreshes. In my javascript code, this is what I h ...

The functions.php file is failing to execute the JavaScript files located in the js folder

I've been attempting to incorporate a JS accordion into my Wordpress blog, but I seem to be encountering issues with the accordion.js file not loading through the functions.php file. Interestingly enough, when I manually add the js code in the header ...

Convert the nested JSON structure of pandas into a dataframe

When faced with a nested JSON output, is there a way to convert it into a data frame? Specifically, I am looking to extract the "Quotes" level and transform it into rows within a data frame. Within the nested structure, there are two main levels: "Quotes" ...

I am looking to remove identical innerText values from two arrays using JavaScript

Is it possible to use JavaScript to remove the "added" className of an element with the same innerText when the delete button (.btn-wrap>li>button) is clicked? <div class="table"> <ul> <li class="added">l ...

Encountering a high volume of requests error while attempting to retrieve data from the API using the NodeJS backend, yet functioning properly on the React

While attempting to retrieve data from https://api.solscan.io/chaininfo using a NodeJS backend application, I encountered an error stating 429: Too many requests. Interestingly, the same API functions without any issues when utilized in a React frontend a ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Utilizing JSON to transfer PHP array data for display using JQuery

Currently, I am working on a jQuery script that is responsible for fetching a PHP array from the MySQL database and converting it into a JSON object. The process is functioning correctly, as I can successfully output the raw JSON data along with the keys. ...

What is the best approach for scaling @material-ui Skeleton in a grid row with variable heights?

I am working on creating a grid of Avatar images with a transition state where I want to show a skeleton representation of the image. To achieve this, I am using @material-ui/lab/Skeleton. The issue I'm facing is that since my images are set to autos ...

Issue with vue.js not recognizing the 'require' function

I am a newcomer to Vue and I am trying to create a basic SPA using Vue without vue-router. Following the example of vue-2.0-simple-routing-example, I am attempting to load pages using require(dynamicPathToFile+'.vue'). However, this approach is n ...

How can AngularJS handle multiple views sharing the same controller and ensure that the controller is executed only once?

Currently, I am facing a situation where I have two separate views that I would like to control within a single controller. The issue is, the controller is being executed twice. Is there a way to link multiple views to the same controller without the cont ...

Why is it possible to assign a variable holding a char array to a pointer in C, but attempting to take the address of that same pointer is not allowed?

Let's examine the following code snippet: char stringy[] = "There's too much confusion, I can't get no relief!"; char *pStringy; pStringy = stringy; It's interesting how this code compiles without any errors. Although stringy ...