Filter an array of objects in Javascript and determine the number of elements that meet the filtering criteria

I have a collection of various objects structured like the following:

[{
   color:'red',
   'type':'2',
   'status':'true'
 },
 {
   color:'red',
   'type':'2',
   'status':'false'
 }]

My goal is to filter the elements by status and then tally the filtered results. For example, if the status is false, then return 1.

Below is the code I attempted, but I'm unsure of my approach:

for (i = 0; i < check.length; i++) {
  var check2;

  console.log(check[i].isApproved);
  (function(check2) {
    return check2 = check.filter(function(val) { 
        return val == false 
    }).length;
  })(check2)

  console.log('again Rides',check2);
}

Answer №1

To clarify, you are looking to tally the instances where the status is 'false'. It's important to note that the values in status are strings.

var items = [
  { color:'red', 'type':'2', 'status':'true' }, 
  { color:'red', 'type':'2', 'status':'false' } 
];

var countMatches = items.filter(function(item){
    return item.status === 'false';
}).length

console.log(countMatches);

Answer №2

Consider the following data set:

const elements = [
  { color:'blue', type:'1', status:'true' }, 
  { color:'blue', type:'2', status:'false' } 
];

Here are a couple of methods to address the issue:

Utilizing reduce

const falseCount = elements.reduce((num, element) => element.status === 'false' ? num+1 : num, 0)

Using filter approach

const falseCount = elements.filter(item => item.status === 'false').length;

Please take note that as per

const elements = [
  { color:'red', type:'2', status:'true' }, 
  { color:'red', type:'2', status:'false' } ,
  { color:'red', type:'2', status:'false' } ,
  { color:'green', type:'1', status:'false' } ,
  { color:'red', type:'1', status:'true' } 
]

const falseNb = elements.reduce((n, e) => e.status === 'false' ? n+1 : n, 0)

document.getElementById('result1').innerHTML = falseNb

const falseNbFilter = elements.filter(e => e.status === 'false').length

document.getElementById('result2').innerHTML = falseNb
body { background: #333; color: #0f0; font-family: monospace}
<pre>
[
  { color:'red', type:'2', status:'true' }, 
  { color:'red', type:'2', status:'false' } ,
  { color:'red', type:'2', status:'false' } ,
  { color:'green', type:'1', status:'false' } ,
  { color:'red', type:'1', status:'true' } 
]
</pre>
Result with Reduce => <span id='result1'></span><br><br>

Result with Filter => <span id='result2'></span>

Answer №3

To determine the number of objects with a specific status, you have two options: you can either count them directly or use a filter and find the length of the resulting array.

var count = 0;
var arr = [{color:'red', type:'2', status:'true'},
           {color:'red', type:'2', status:'false'} ];
// Demonstrating the robustness of filtering. For simplicity, you could achieve
// the same result in a loop if you don't require the subarray. 
var filtered = arr.filter ( function ( d ) {
    // Since your objects contain string values for 'status', checking against strings is necessary.
    // If the status was boolean, you'd use if ( d.status ) { ... }
    count++;
    return d.status === 'false';
});

// Both counts should be equivalent, representing the number of objects with status 'false'
console.log ( count );
console.log ( filtered.length );
// This will display the subarray of objects with status set to 'false'
console.log ( filtered );

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

Navigating through property objects in Vue: accessing individual elements

I am a newcomer to Vue and after reviewing other questions on this platform, I am struggling to figure out how to pass an object to a child component and reference individual elements within that object. My goal is to have access to all elements of the obj ...

Store vueJs data in browser's localStorage

Is there a way to save the state of my game even after a page refresh using local or session storage? I've successfully stored wins in localStorage, but I'm struggling to keep the table with "X" and "O" in the same spot after a refresh. Any sugge ...

tips for replacing multiple route parameters in Angular using the replace function

I am facing an issue when trying to replace multiple parameters using the angular replace function. The problem is that the function only detects the first parameter. For example, if I have this route admin/management/{type}/card/{id}, and use the route.r ...

Removing dropdown lists from input forms can be achieved without using jQuery by utilizing vanilla JavaScript

Looking to build a custom HTML/JavaScript terminal or shell. Interested in utilizing an input box and form to interact with JavaScript functions/commands. Unsure of how to eliminate the drop-down menu that appears after previous inputs. Pictured terminal: ...

Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows: subjects | ----------------------------------------------- ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

Angular 5 arrays within arrays

I'm currently facing an issue with using ngFor on a nested JSON output. The outer loop is working as expected, but the inner loop is not functioning properly. Below is my code snippet: Typescript file import { Component, OnInit } from '@angula ...

Error message 800A03EA in Windows Script Host encountered while running Express.js script

I'm currently diving into the world of JavaScript development, following along with the guidance provided in the book called "JavaScript Everywhere." The book instructs me to execute the following code: const express = require('express' ...

Laravel and Vue: tackling pagination issues in a Vue.js and Laravel application

I'm struggling with getting Laravel pagination to function properly. Although I attempt to access results from different pages, I find that I can only retrieve the first page. Even when I click on page 2, upon checking the request payload, it always i ...

Accessing the identical file concurrently through ajax 12 times

I'm facing an issue with loading the same external file multiple times on a page. When the page loads, it takes up to a minute due to large load times. I've tried using Ajax to load each file individually, but running a loop to load all files at ...

The toggle feature doesn't seem to be working properly in Bootstrap 5

I've tested it in the latest Bootstrap version and still can't get it to work. I even switched to version 5, but the toggle functionality remains a problem. I've tried various solutions from StackOverflow with no luck ** I've added all ...

Fetching various data from MongoDB using NodeJS and presenting it in Jade(Pug) template

I am working with MongoDB collections and need to showcase them on my website, creating a dynamic page that updates automatically. Specifically, I am dealing with team members' information in the database. Here is an example of how my collections loo ...

The element 'flat' is not found within the specified type

My challenge involves utilizing the flat() method in a TypeScript script. In my tsconfig.json file, I have set the target to es2017 and defined an interface for the input variable. However, I keep encountering this error message: Property 'flat' ...

Testing infinite scrolling with the help of protractor

It seems like the infinite scrolling feature in ng-grid is not exactly infinite, but it's the closest comparison I could come up with for what I am observing. In our application, we are using ng-grid to display data in a table with approximately 170 ...

Obtain the value of a two-handle slider using jQuery

Here is the HTML and JS setup I have for implementing a jQuery two-handle range slider: .html <p> <input class="amount" readonly style="border:0; color:black; background: transparent; text-align: center;" type="text"> </p> <div cla ...

Simple yet perplexing JavaScript within an Angular directive

In the tutorial, the author explains that each element in the stars array contains an object with a 'filled' value, which is determined as true or false based on the scope.ratingValue received from the DOM. directive('fundooRating', fu ...

I'm looking to add CSS transitions, like fade-ins, to a list of items in React in a way that the animations occur one after the other upon rendering. How can this be achieved?

I've scoured the depths of Stack Overflow and combed through countless pages on the internet in search of an answer to my query, but alas, I have not found a solution. So, my apologies if this question is a duplicate. Here's my conundrum: https ...

What is the best way to convert a requested JSON array into a CSV file using Python?

I'm completely new to programming and I'm having trouble saving my data. Currently, I'm working on a website for a scientific experiment where users are required to click 'yes' or 'no' buttons to indicate their recognitio ...

Sending files to different URLs based on their type for upload

I've been working with Jquery File Upload and I've implemented some coffeescript that appears like this: $('.fileupload').fileupload dataType: "json" add: (e, data) -> file = data.files[0] types = /(\.|\/)(gif|jpe? ...