How to count object in array

How to count object in array


I had an Array like this

storage:  [
{ data: '1', status: '0' },
{ data: '2', status: '0' },
{ data: '3', status: '0' },
{ data: '4', status: '0' },
{ data: '5', status: '0' },
{ data: '6', status: '0' },
{ data: '7', status: '1' },

How to count there is only six data that have status: 0 on javascript? Please share a refrece too if you know it. Thanks :slight_smile:


Set up a counter, and loop through the items in the array. If status is 0, add one to the counter. Once the loop is done, return the counter. The loop could be any one of the different looping constructs (for, while, reduce), but eg

function statusCounter(inputs) {
  let counter = 0;
  for (const input of inputs) {
    if (input.status == 0) counter += 1;
  return counter;

Or reduce

inputs.reduce((counter, {status}) => status == 0 ? counter + 1 : counter, 0);


You can use the filter function of the array prototype to do this:

const count = storage.filter(item => item.status === '0').length;

This is the exact same thing, with a more verbose syntax.
The functio
n will return any item that passes the test back to a newly created array.

const noStorage = storage.filter(function(item){
  if(item.status === 0) {
    return true;
  } else {
    return false;
const count = noStorage.length;


Thanks @collinstommy @DanCouper your both code are work great,

.filter are create a new arrays right? and what about reduce?


Just comparing reduce and filter, the best way to do it i think with reduce since it resulting single output without creating a new array, best for lot of array in data.

But two code are just work, thanks


So reduce takes an array of things and converts it to another type of thing - that’s why there’s no creation of a new array: in this case, an array is being contested to a number. Difference between that and filter will be minimal tbh, as you always have to iterate through the entire array anyway; filter is generally much easier to understand if you’re reading the code (note filter is just a specialised version of reduce)


Hello, i think I must reply this and doesn’t make any new post cause its still the same topic.

let me updated the array.

var storage =  [
{ data: '1', status: '0', price: 10},
{ data: '2', status: '0', price: 10},
{ data: '3', status: '1', price: 18},

I only want to count the price that had the status zero so the output would be 20.

what i tried?

var actualProduct = storage.reduce((value, {status}) => {
  status == 0
  return counter

but the output are just :

[object Object] {
  data: "1",
  price: 10,
  status: "0"

I think reduce stop, when its found the matching array.

actualy i can do that with filter storage.filter(value => value.status == 0)

but do you guys had any solution? how to get it with reduce() ?