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 i… Answer from DanCouper on forum.freecodecamp.org
🌐
freeCodeCamp
freecodecamp.org › news › how-to-count-objects-in-an-array
How to Count Objects in an Array
June 2, 2020 - const 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' }, ]; const count = storage.filter(function(item){ if (item.status === 0) { return true; } else { return false; } }); /* [ { data: '1', status: '0' }, { data: '2', status: '0' }, { data: '3', status: '0' }, { data: '4', status: '0' }, { data: '5', status: '0' }, { data: '6', status: '0' } ] */ Now that you've filtered out the object with status: '1', just call the length() method on the new array to get the total count of objects with status: '1':
🌐
Stack Abuse
stackabuse.com › javascript-how-to-get-the-number-of-elements-in-an-array
JavaScript: How to Get the Number of Elements in an Array
May 4, 2022 - In this tutorial, learn how to get the number of elements in a JavaScript array/list, using the length property, a manual for loop with a counter, how to count elements of nested arrays by flattening arrays and manually counting through, etc. with practical code examples.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-count-elements-in-array-with-condition
Count Elements in an Array that match a Condition using JS | bobbyhadz
Copied!const arr = [1, 11, 2, 12, 3, 13]; let count = 0; for (const element of arr) { if (element > 10) { count += 1; } } console.log(count); // 👉️ 3 ... The for...of statement is used to loop over iterable objects like arrays, strings, Map, Set and NodeList objects and generators.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › group and count values
How can I group and count values in a JavaScript array? - 30 seconds of code
August 19, 2024 - It's also fairly straightforward to implement, both for primitive and complex values, using JavaScript's Array methods. You can use Array.prototype.reduce() to create an object with the unique values of an ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › count-occurrences-of-all-items-in-an-array-in-javascript
Count Occurrences of All Items in an Array in JavaScript - GeeksforGeeks
The reduce method counts occurrences by iterating through the array. It adds each item to an object (acc) and increments its count or initializes it to 1 if it doesn’t exist.
Published   July 23, 2025
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › How-to-count-JavaScript-array-objects
How to count JavaScript array objects?
In this approach, we will use the for loop to count the total number of objects in the array. Users can iterate through every element of the array and check the type of every element using the instanceof operator. They can initialize the length variable with 0 to store a total number of objects.
🌐
sebhastian
sebhastian.com › javascript-counting
JavaScript - counting array and object elements with certain conditions | sebhastian
May 22, 2021 - The .length parameter of Array type data can be used to count how many elements you have inside an array or object variable.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › length
Array: length - JavaScript | MDN
The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
🌐
QuickRef.ME
quickref.me › home › how to count by the properties of an array of objects in javascript - quickref.me
How to count by the properties of an array of objects in JavaScript - QuickRef.ME
In this Article we will go through how to count by the properties of an array of objects only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
Top answer
1 of 3
1
This code will sort the array then loop through it to build an output array containing the count of each group/complexity per your requirements. · var arr = [ · {group: "AA", complexity: "Simple"}, · {group: "AA", complexity: "Complex"}, · {group: "AA", complexity: "Simple"}, · {group: "BB", complexity: "Simple"}, · {group: "AA", complexity: "Medium"} · ]; · var outputArr = []; · var outputObj = {}; · var group = ''; · var comp = ''; · var count = 0; · //first re-order array on group and complexity · arr.sort(function (a, b) { · return a.group.localeCompare(b.group) || a.complexity.localeCompare(b.complexity); · }); · //loop through the sorted array to build the output array, comparing group and complexity previous values to establish correct count · for(var i=0; i<=arr.length; i++){ · if(group == arr[i].group.toString()){ · if(comp == arr[i].complexity.toString()){ · count++; · } · else{ · outputObj ={ · 'group' : arr[i-1].group.toString(), · 'complexity' : arr[i-1].complexity.toString(), · 'count' : count · }; · outputArr.push(outputObj); · comp = arr[i].complexity.toString(); · count = 1; · } · } · else{ · if(count == 0){ · group = arr[i].group.toString(); · comp = arr[i].comp.toString(); · count = 1; · } · else{ · outputObj ={ · 'group' : arr[i-1].group.toString(), · 'complexity' : arr[i-1].complexity.toString(), · 'count' : count · }; · outputArr.push(outputObj); · group = arr[i].group.toString(); · comp = arr[i].complexity.toString(); · count = 1; · } · } · } · gs.print(JSON.stringify(outputArr));
2 of 3
0
Your example adds to confusion but "arr.length" will return you the number of objects inside of it.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-count-occurrences-of-each-element-in-array
Count Occurrences of each Element in Array in JavaScript | bobbyhadz
On each iteration, we check if the current array element exists as a key in the object. If the key exists, we increment its value by 1, otherwise, we initialize the key to 1. You can also use a Map object instead of a regular object. ... Copied!const arr = ['b', 'a', 'c', 'b', 'b', 'a']; const count = arr.reduce((accumulator, value) => { accumulator.set(value, (accumulator.get(value) || 0) + 1); return accumulator; }, new Map()); // 👇️ Map(3) { 'b' => 3, 'a' => 2, 'c' => 1 } console.log(count); console.log(count.get('a')); // 👉️ 2 console.log(count.get('b')); // 👉️ 3 console.log(count.get('c')); // 👉️ 1 // 👇️ [ 'b', 'a', 'c' ] console.log([...count.keys()]); // 👇️ [ 3, 2, 1 ] console.log([...count.values()]); // 👇️ [ [ 'b', 3 ], [ 'a', 2 ], [ 'c', 1 ] ] console.log([...count.entries()]);
🌐
Reddit
reddit.com › r/learnjavascript › using reduce method to count the occurrence of every element in an array.
r/learnjavascript on Reddit: Using reduce method to count the occurrence of every element in an array.
December 6, 2022 -

Learning JS and I feel pretty stumped about this reduce method exercise. The video I saw counts the occurrence of every element in an array.

What does total[item] = (total[item] || 0) +1

From my understanding, the first argument in a reduce method is the previous value and the second argument is the current value. How can we have previousValue[currentValue]?

what does this mean: previousValue[currentValue] = (previousValue[currentValue] || 0) +1

Thank you!

--------------- Exercise -------------

const toys = ['car', 'dog', 'car', 'truck', 'boat']

let countToys = toys.reduce((total, item) => {total[item] = (total[item] || 0) +1

return total}, {})

console.log(countToys)

Top answer
1 of 1
1
Well, basically inside the callback passed to "reduce" you have to arguments."total" in this case it's an object. This variable will be passed to all of the iterations made by reduce.Then the "item" is just a current item in the toys array.In side the callback you assign value to a property that will be the number of occurances of given string in the toys array. That's why it's total[item] as a particular string (the item) from this array will be the "key". Then in the assignment total[item] = (total[item] || 0) +1; you're setting a value. If there's already some value under this "key" in the total object than it will take the existing value, otherwise it will be the second option, 0. After that it increments it by one. That's rather straightforward. The last argument in call to "reduce", those buckles are the "starting value" of what that "total" argument will be, so an object. I guess you could visualize it like that: const toys = ['car', 'dog', 'car', 'car'];let countToys = toys.reduce((total, item) => {total[item] = (total[item] || 0) +1; return total}, {}); Then the reduce will work like that Iteration 1: total = {} item = 'car' (total['car'] || 0) -> returns 0 as the total['car'] doesn't exist yet, we're creating it right now total['car'] = 0 + 1 Iteration 2: total = {car: 1} item = 'dog' (total['dog'] || 0) -> will return 0 as the total['dog'] doesn't exist yet total['dog'] = 0 + 1 Iteration 3: total = {car: 1, dog: 1} item = 'car' (total['car'] || 0) -> will return 1 as the total['car'] exists and has value equal to 1 total['car'] = 1 + 1 Iteration 4: total = {car: 2, dog: 1} item = 'car' (total['car'] || 0) -> will return 2 as the total['car'] exists and has value equal to 2 total['car'] = 2 + 1 So then after going through this array with reduce you'd get total = {car: 3, dog: 1}
🌐
DEV Community
dev.to › aohibbard › counting-array-of-arrays-2j8l
Counting Array of Arrays - DEV Community
October 9, 2020 - In both cases, it is extremely helpful to use JavaScript's [Object.keys() method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), yielding an array of the object keys that can be filtered to get ...
🌐
TutorialsPoint
tutorialspoint.com › javascript-count-the-number-of-unique-elements-in-an-array-of-objects-by-an-object-property
JavaScript Count the number of unique elements in an array of objects by an object property
In JavaScript, when dealing with arrays of objects, it’s common to need to extract specific values based on object properties and count how many unique occurrences exist for a particular property. Whether you're processing a list of users, products,
Top answer
1 of 16
517

[this answer is a bit dated: read the edits, in the notion of 'equal' in javascript is ambiguous]

Say hello to your friends: map and filter and reduce and forEach and every etc.

(I only occasionally write for-loops in javascript, because of block-level scoping is missing, so you have to use a function as the body of the loop anyway if you need to capture or clone your iteration index or value. For-loops are more efficient generally, but sometimes you need a closure.)

The most readable way:

[....].filter(x => x==2).length

(We could have written .filter(function(x){return x==2}).length instead)

The following is more space-efficient (O(1) rather than O(N)), but I'm not sure how much of a benefit/penalty you might pay in terms of time (not more than a constant factor since you visit each element exactly once):

[....].reduce((total,x) => (x==2 ? total+1 : total), 0)

or as a commenter kindly pointed out:

[....].reduce((total,x) => total+(x==2), 0)

(If you need to optimize this particular piece of code, a for loop might be faster on some browsers... you can test things on jsperf.com.)


You can then be elegant and turn it into a prototype function:

[1, 2, 3, 5, 2, 8, 9, 2].count(2)

Like this:

Object.defineProperties(Array.prototype, {
    count: {
        value: function(value) {
            return this.filter(x => x==value).length;
        }
    }
});

You can also stick the regular old for-loop technique (see other answers) inside the above property definition (again, that would likely be much faster).


2017 edit:

Whoops, this answer has gotten more popular than the correct answer. Actually, just use the accepted answer. While this answer may be cute, the js compilers probably don't (or can't due to spec) optimize such cases. So you should really write a simple for loop:

Object.defineProperties(Array.prototype, {
    count: {
        value: function(query) {
            /* 
               Counts number of occurrences of query in array, an integer >= 0 
               Uses the javascript == notion of equality.
            */
            var count = 0;
            for(let i=0; i<this.length; i++)
                if (this[i]==query)
                    count++;
            return count;
        }
    }
});

You could define a version .countStrictEq(...) which used the === notion of equality. The notion of equality may be important to what you're doing! (for example [1,10,3,'10'].count(10)==2, because numbers like '4'==4 in javascript... hence calling it .countEq or .countNonstrict stresses it uses the == operator.)

Caveat: Defining a common name on the prototype should be done with care. It is fine if you control your code, but bad if everyone wants to declare their own [].count function, especially if they behave differently. You may ask yourself "but .count(query) surely sounds quite perfect and canonical"... but consider perhaps you could do something like [].count(x=> someExpr of x). In that case you define functions like countIn(query, container) (under myModuleName.countIn), or something, or [].myModuleName_count().

Also consider using your own multiset data structure (e.g. like python's 'collections.Counter') to avoid having to do the counting in the first place. This works for exact matches of the form [].filter(x=> x==???).length (worst case O(N) down to O(1)), and modified will speed up queries of the form [].filter(filterFunction).length (roughly by a factor of #total/#duplicates).

class Multiset extends Map {
    constructor(...args) {
        super(...args);
    }
    add(elem) {
        if (!this.has(elem))
            this.set(elem, 1);
        else
            this.set(elem, this.get(elem)+1);
    }
    remove(elem) {
        var count = this.has(elem) ? this.get(elem) : 0;
        if (count>1) {
            this.set(elem, count-1);
        } else if (count==1) {
            this.delete(elem);
        } else if (count==0)
            throw `tried to remove element ${elem} of type ${typeof elem} from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)`;
            // alternatively do nothing {}
    }
}

Demo:

> counts = new Multiset([['a',1],['b',3]])
Map(2) {"a" => 1, "b" => 3}

> counts.add('c')
> counts
Map(3) {"a" => 1, "b" => 3, "c" => 1}

> counts.remove('a')
> counts
Map(2) {"b" => 3, "c" => 1}

> counts.remove('a')
Uncaught tried to remove element a of type string from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)

sidenote: Though, if you still wanted the functional-programming way (or a throwaway one-liner without overriding Array.prototype), you could write it more tersely nowadays as [...].filter(x => x==2).length. If you care about performance, note that while this is asymptotically the same performance as the for-loop (O(N) time), it may require O(N) extra memory (instead of O(1) memory) because it will almost certainly generate an intermediate array and then count the elements of that intermediate array.

2 of 16
152

Modern JavaScript:

Note that you should always use triple equals === when doing comparison in JavaScript (JS). The triple equals make sure, that JS comparison behaves like double equals == in other languages (there is one exception, see below). The following solution shows how to solve this the functional way, which will ensure that you will never have out of bounds error:

// Let has local scope
let array = [1, 2, 3, 5, 2, 8, 9, 2]

// Functional filter with an Arrow function
// Filter all elements equal to 2 and return the length (count)
array.filter(x => x === 2).length  // -> 3

The following anonymous Arrow function (lambda function) in JavaScript:

(x) => {
   const k = 2
   return k * x
}

may be simplified to this concise form for a single input:

x => 2 * x

where the return is implied.

Always use triple equals: === for comparison in JS, with the exception of when checking for nullability: if (something == null) {} as it includes a check for undefined, if you only use double equals as in this case.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
The constructor function that created the instance object. For Array instances, the initial value is the Array constructor. ... Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for with statement-binding purposes. These properties are own properties of each Array instance. ... Reflects the number of elements in an array. ... Returns the array item at the given index. Accepts negative integers, which count ...
🌐
Sling Academy
slingacademy.com › article › javascript-count-the-occurrences-of-elements-in-an-array
JavaScript: Count the occurrences of elements in an array - Sling Academy
This concise, straight-to-the-point article shows you 3 different ways to count the occurrences of elements in a given array in JavaScript. ... for loop to iterate over the array and update the count for each element. We will create an object to store the count and print it out at the end.