Operating on JSON objects/arrays according to their values

I am working on developing a function that accepts a string as its first argument and a JSON LIST as its second argument:

[
    {
        "date": "09/09/18",
        "how_many": 11,
        "species": "XXXXX"
    },
    {
        "date": "04/11/17",
        "how_many": 41,
        "species": "TTTTTT"
    },
    {
        "date": "17/03/18",
        "how_many": 30,
        "species": "DDDDDDDD"
    },
    {
        "date": "17/08/18",
        "how_many": 31,
        "species": "XXXXX"
    },
]

If the input string matches with any of the values under "species" key in each JSON entry, it will calculate the number of occurrences.

In simple terms, I need to create a function that counts how many times the input string appears in the list of objects based on the value of the "species" key.

Answer №1

If you're looking to streamline your array manipulation, consider using the Array.reduce method.

The official documentation explains that reduce() applies a reducing function to each element in the array to produce a single output value:

The reduce() method executes a reducer function (which you define) on every item of the array, resulting in a final output value.

The value returned by your reducer function is added to an accumulator, which retains its value throughout the iterations and eventually becomes the ultimate resultant value.

EXPLANATION

By using the reduce function, you can condense an array into a single value, such as the sum of all matching species. The initial sum value is set to 0, and during iteration, the function checks if the object's species matches the provided value. If there's a match, it adds the how_many value to the total sum.

ES6

let list = [{"date":"09/09/18","how_many":11,"species":"XXXXX"},{"date":"04/11/17","how_many":41,"species":"TTTTTT"},{"date":"17/03/18","how_many":30,"species":"DDDDDDDD"},{"date":"17/08/18","how_many":31,"species":"XXXXX"}];

function findOccurences(str, arr) {
  return arr.reduce((a,c) => a + (c.species === str ? c.how_many : 0), 0);
}

console.log(findOccurences("XXXXX", list));

ES5

let list = [{"date":"09/09/18","how_many":11,"species":"XXXXX"},{"date":"04/11/17","how_many":41,"species":"TTTTTT"},{"date":"17/03/18","how_many":30,"species":"DDDDDDDD"},{"date":"17/08/18","how_many":31,"species":"XXXXX"}];

function findOccurences(str, arr) {
  // "a" represents the accumulator, "c" represents the current value
  return arr.reduce(function(a, c){
    // If the object's species matches the provided value ("str"), add its how_many value to the total sum
    if(c.species === str) {
      a += c.how_many;
    }
    return a;
  }, 0);
}

console.log(findOccurences("XXXXX", list));

Answer №2

Give this a shot:

function getOccurrenceCount(inputStr, dataList) {
   var matchingItems = dataList.filter(item => item.type === inputStr);
   return matchingItems.length;
}

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

Exploring the functionalities of Express and Socket.io

I am new to creating a Node.js app using express V 3.4.8 and socket.io V 0.9.16 to display a map with markers showing where users are connecting to the site. I am doing this to learn more about node.js and how to incorporate maps into my projects. However, ...

What is the best way to transmit data as a reply from a Node.js server to an AJAX client?

Currently, I am utilizing a function to transmit data regarding an HTML element as an object: function postItem(input) { $.ajax({ type: "POST", url: "http://localhost:8080", data: input, success: function(message) { Hconsole.log(&a ...

Troubleshoot: jQuery Datalink functionality not functioning properly with object methods

Within my JavaScript code, I have defined an object that includes various properties and an instance method that calculates a value based on two of those properties. To synchronize the object's property values with form elements in the UI, I am utili ...

Retrieve only ObjectIds that are embedded in an Array using MongoDB's .find() method

I am looking to extract only the ObjectIds from a specific document that is nested within the projects Array. I am working on creating a database where each user will have their own set of projects. Thank you! db.users.find().pretty() { "_id" : Obje ...

What exactly happens behind the scenes when JSON.stringify() is called?

How does the replacer argument function extract keys and values from an object's value and map them to its key and value arguments in the JSON.stringify(value, replacer, space) method? I have grasped that the key of the object becomes the key paramet ...

The feature to disable legend click in Chart.js does not activate unless the specific condition is met

I am working with chartjs and have encountered a scenario where I need to disable actions when a legend item is clicked, but only under certain conditions. I was able to accomplish this using the following code snippet: legend: { position: 'right& ...

What is the best way to send a promise back from my service to my controller?

While I have posed this question in various forms, I now find myself stuck with a piece of code that contains an elusive bug. My Angular service looks like this: .service("lookupDataService", [ '$q', '$http', '$timeout&ap ...

Retrieve a specific item from the JSON dataset

Currently, I am in the process of working on my own project using jQuery, AJAX, and JSON. My goal is to retrieve data from the TMDB API by allowing users to search for a specific term, such as the movie "Fight Club." The desired outcome is to display a mov ...

How can I properly choose distinct values for an individual attribute from a JavaScript array containing objects?

Let's imagine a scenario with an array of JavaScript objects like this: var data = [ {category : "root", type: "qqqqq", value1: "aaaaa", value2: "zzzzz"}, {category : "root", type: "qqqqq", value1: "aaaaa", value2: "xxxxx"}, {category : " ...

Encountering an Error When Trying to Read a JSON String: TypeError - string indices must be

I have been working on a program that involves reading a JSON string through a user interface and using it to perform various functions, such as breaking down mathematical equations. However, I am encountering an error message: "TypeError: string indice ...

When the request's credentials mode is set to 'include', the 'Access-Control-Allow-Origin' header in the response should not be using the wildcard '*'

I am encountering an issue with my socket.io server as I am unable to connect to it from my local HTML file on my Mac. Error: Failed to load : The 'Access-Control-Allow-Origin' header in the response is causing a problem due to the wildcard ...

Representation of data format obtained from a method for selecting an element with a data URL in JQGrid

Can you explain the JSON data format that is returned to a select element using the dataUrl option? Below is the script used to set parameters for the select option: { name: 'client', index: 'client', jsonmap: 'proje ...

Using Node.js, express, jade, highcharts, and a 2D array

Greetings, I am relatively new to the realm of javascript/node.js/express/jade/highcharts etc... The predicament at hand is as follows: I have a template that takes in a few parameters which are pre-processed in my router code. These parameters are group ...

Updating the innerHTML of a button with a specific id using Javascript is not possible due to it being "null."

My objective is to create a button that, when clicked, triggers a function to alter the styling of the HTML tag as well as the text or innerHTML of the button itself. Sounds simple enough, right? Unfortunately... The HTML: <!DOCTYPE html> <html& ...

Strategies for preserving context throughout an Ajax request

In my project, I am looking to implement an Ajax call that will update a specific child element within the DOM based on the element clicked. Here is an example of the HTML structure: <div class="divClass"> <p class="pClass1">1</p> &l ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Tips for showing JSON results on an ASP.NET webpage retrieved from an SQL database

I need to retrieve data from SQL in C# and display it as JSON output on a .aspx page without using ASP.NET web service. { "dept_updates": [ { "id":"11", "subject":"zzz", "utime":"Saturday 4th July 2 ...

Reopen a Kendo UI dialog

Currently, I am utilizing Kendo UI, and my goal is to display a modal dialog when a button is clicked. The issue I am facing is that it works perfectly the first time around. However, upon closing the dialog and attempting to reopen it by clicking the butt ...

Why is the useHistory hook in React failing to function properly?

When I try to launch my web application using npm start, an error occurs stating that the useHistory hook has not been downloaded, despite having installed the latest version of react-router-dom. Can someone explain why this is happening? Here is a screens ...

Simple React application

I'm delving into the world of ReactJS, trying to create a simple webpage with it. However, as a beginner, I seem to have encountered an issue with the code snippet below. It's not functioning correctly, and I can't figure out why. Can someon ...