Determine the quantity of elements within a JSON object based on specified criteria

I am seeking a way to count the number of items in an array of JSON objects that meet specific conditions. The structure of my array is as follows:

array = [{
            name: 'Bob',
            age: 24
           },
          ....,
          {
            name: 'Mary',
            age: 23
           }]

Instead of iterating through the entire array, I would like to find an expression similar to a database query for simplicity and elegance:

db.myCollection.find({ age: 23 }).count()

Are there any recommended best practices for this task? I have considered using the underscore library but haven't found exactly what I need.

Your assistance is greatly appreciated.

Answer №1

There's a simple way to achieve this task without relying on any external libraries or using loops:

array.filter(function(value) { return value.age === 23 }).length;

Furthermore, if you're using ES6, the code can be even more concise:

array.filter(value => value.age === 23).length;

Answer №2

In my original post, it appears that you are interested in using the _.size method.

_.chain(json)
 .find({age: 23})
 .size()
 .value();

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

I am looking to retrieve information from mongodb and then transform it into a JSON object using node.js. Can you guide

I am on a mission to retrieve data from a MongoDB database and transform it into a JSON object in Node.js. The goal is to be able to easily manipulate this data as if it were a simple JSON object. Here's the current code snippet I'm working with: ...

avoiding the initiation of a new ajax request while a previous one is still in progress

Attempting to create a function that retrieves data from a server on scroll. The function would look something like this... function onscrollend() { $.ajax({ }); } Feeling a bit perplexed about how to verify if the old .ajax() call is still in pr ...

What is the best way to modify specific data retrieved from an API using Angular?

After successfully listing some data from an API using ngFor, I am facing an issue with editing the data. Whenever I click the edit button, it edits the entire data instead of just the specific row. Below is the code snippet for reference: HTML <table ...

Shift the sleek navigation arrows to the interior of the slides

Is there a way to relocate the navigation arrows on the slider images? I have tried various methods found online with no success. Currently using ASP.NET, but doubt it matters. Employing the latest version of SLICK. Here is the HTML code snippet: <%@ ...

In a JavaScript project, encountering an error when using FB.logout that states "The expression is undefined and not a function."

Seeking to integrate Login with FB into my react website. FB.init({ appId : app_id, cookie : true, xfbml : true, version : 'v5.0' }); Followed by FB.getLoginStatus(({status}) => { if (status === 'conn ...

Choosing various files from separate directories within an HTML input type="file" element

Is there a way to select multiple files from various directories using the HTML input type="file" element? I have been searching for resources on how to do this without any luck. Are there any npm packages that can assist with achieving this functionalit ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

displaying an AngularJS ng-repeat as empty following the completion of an Ionic loading operation

When using $ionicLoading to load the news page, a message is displayed if no news is found: <div ng-show="!news.length" class="empty"> Nothing to show ! </div> However, there is an issue where the empty div (Nothing to show !) is visible durin ...

The JSON outcome format is not accurate

My goal is to fetch JSON data from SQL Server by using FOR JSON PATH, with the desired output as follows: ["5.0","5.5","6.0","6.5","7.0","7.5","8.0","8.5","9.0"," ...

What could be causing this JS/jQuery to affect numerous inputs at once?

Everything is working smoothly with the code in the 'phone' input field. It formats the phone number correctly as the user types. However, there seems to be an issue with the event listener being added to another input named 'twofactor' ...

What is the best way to transfer data from one worker to all the others in node.js?

Upon node boot up, I initialize an in-memory JavaScript object. This node app runs on multiple cores using the cluster module. When an HTTP request is received, it is handled by one of the worker threads which then modifies the value of the JavaScript ob ...

Implementing a separated front-end and back-end for an application

My web app consists of two separate components: An API built on the Place Framework that handles requests of type /api/* for any client. A decoupled front end created with AngularJS using grunt build. Currently, the front end communicates with the API. ...

At what point is the ajax call considered fully executed?

Whenever a client makes an AJAX call, they upload data to the server (HTTP request) and then receive data from the server (HTTP Response). Once the clients have received all the data, the AJAX request is considered successful, and the success callback func ...

Dealing with Request Disconnection in a Node.js and Express Application

I have a node/express application and I am looking for a way to detect unexpected interruptions in the connection. I have attempted using the following code: req.on('close', function () { //this handles browser/tab closure scenarios }) Howev ...

Best practice for updating Form.Control text using a custom onChange method

Today, I observed a unique behavior while utilizing a custom onChange in a Form.Control. The text in the field no longer updates when a file is selected. I thoroughly checked the Git documentation HERE, but unfortunately, it does not provide information on ...

There was an issue encountered when attempting to access the stackoverflow api

I am currently attempting to retrieve all questions tagged with ipv4 from stackoverflow using the stackoverflow API. However, I encountered the following error message: No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

Utilize jQuery to generate a dynamic table within a Razor view

I am trying to implement a table in a razor view. <div class="row" style="margin-left:80%"> @if (ViewBag.IsGlobal == 1) { <script> $(document).ready(function () { $("#btnViewLocal").prop("disabled",t ...

Where do JQuery and framesets vanish to?

Whenever I attempt to use the console to create an element with the tag frameset, it returns no result: $('<div id="content" data-something="hello" />') => [<div id=​"content" data-something=​"hello">​</div>​] $(&apo ...

Developing AngularJS components with proper controller inheritance methods

Is there a way to inherit controllers from angular components? In the previous version of Angular, I used $controller or $injector, but how should I approach it when dealing with isolated scopes? ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...