- How to count JavaScript array objects?
- Using the for Loop and instanceof Operator
- Syntax
- Algorithm
- Example
- Count JavaScript array objects.
- Counting total number of array objects in array using the for loop.
- Using the array.filter() Method
- Syntax
- Parameters
- Example
- Count JavaScript array objects.
- Counting total number of array objects in array using the arrays.filter() method.
- How to Count Objects in an Array
- Use a for loop
- Use array methods
- filter()
- reduce()
- Array: length
- Try it
- Value
- Description
- Examples
- Iterating over an array
- Shortening an array
- Create empty array of fixed length
- Array with non-writable length
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
How to count JavaScript array objects?
In this tutorial, we will learn to count JavaScript array objects. The array is the data structure containing the strings, numbers, objects, etc., in JavaScript. The object is the one kind of entity that contains properties and methods related to it. We can access the object’s properties and invoke the object method using the object’s references.
Generally, To find the array length, we can use the array.length() method and it returns the total number of elements that the array includes. But what if we need to count only object elements?
Here, this tutorial has various approaches to counting the total number of object elements in the JavaScript array.
Using the for Loop and instanceof Operator
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. While iterating through the array elements, if they find any entity of type object, they can increase the length by 1.
Syntax
Users can use the syntax below to use for loop and instanceof operator to count array objects.
let objectsLen = 0; for (let i = 0; i < myArr.length; i++) < // if entity is object, increase objectsLen by 1, which is the stores the total number of objects in array. if (myArr[i] instanceof Object) < objectsLen++; >>
Algorithm
- STEP 1 − Create a variable named objectsLen and initialized it with 0.
- STEP 2 − Create an array and add some objects with other elements.
- STEP 3 − To count the number of objects in the array, we iterate through the array using for loop and check for the element type using the instanceof operator
- STEP 4 − If we find an entity of object type, we will add 1 to the objectsLen variable.
- STEP 5 − At last, we will print the objectsLen variable, which is the total number of objects.
Example
In the example below, count the total number of objects in an array. We use for loop to iterate through the array and apply instanceof operator to check the type of the array element.
Count JavaScript array objects.
Counting total number of array objects in array using the for loop.
Using the array.filter() Method
In JavaScript, array.filter() method is used to filter the elements of the array. Users can add the callback function to the method and add some filtering conditions in the callback function. The filtering condition to filter all objects is to check for the element type in our case. Users can check for the type of the object using the typeof operator and return true from the callback function if the entity is a type of object. Otherwise, return false.
The array.filter() method returns the array of all filtered values. So, we will get the array of all objects, and we can measure its length using the .length() method.
Syntax
Users can follow the below syntax for the array.filter() method to count the number of objects.
// filter all entity which type is object let allObject = array.filter((val) => < // checking the type of elements using the typeof operator. if ( typeofval == 'object' ) < return true; >else < return false; >>); LettotalObjects = allObject.length;
Parameters
- array − It is an array of elements that contains the objects’ entities with other elements.
- val − It is an element of the array for which, the user wants to check the type and filter it if the entity is an object.
Example
In the example below, we have used the array.filter() method to filter all objects from the given array. At last, we have calculated the length of the object array, which is returned by the array.filter() method.
Count JavaScript array objects.
Counting total number of array objects in array using the arrays.filter() method.
Users have learned to calculate the object entities in a JavaScript array. The first approach and second approach have the same time complexity. When we take a look at the space complexity of both approaches first approach has lower space complexity and is optimized in a better way.
How to Count Objects in an Array
Knowing how to quickly iterate through an array and count objects is deceptively simple. The length() method will tell you the total number of values in the array, but what if you only want to count those values based on certain conditions?
For example, imagine you have an array like this:
And you only want to count the number of objects with status set to ‘0’ .
Like with just about everything in programming, there are a number of ways to do this. We’ll go through a few of the common methods below.
Use a for loop
Probably the easiest way would be to declare a counter variable, loop through the array, and iterate counter only if status is equal to ‘0’ :
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' >, ]; let counter = 0; for (let i = 0; i < storage.length; i++) < if (storage[i].status === '0') counter++; >console.log(counter); // 6
You could simplify this a bit by using a for. of loop:
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' >, ]; let counter = 0; for (const obj of storage) < if (obj.status === '0') counter++; >console.log(counter); // 6
Also, you could create a function to do the same thing if you have other arrays of objects to count conditionally:
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' >, ]; function statusCounter(inputs) < let counter = 0; for (const input of inputs) < if (input.status === '0') counter += 1; >return counter; > statusCounter(storage); // 6
Use array methods
JavaScript includes a bunch of helpful methods when working with arrays. Each one can be chained to an array and passed different parameters to work with while iterating through the elements in the array.
The two we’ll look at are filter() and reduce() .
filter()
The filter method does just that – it iterates through each element in the array and filters out all elements that don’t meet the condition(s) you provide. It then returns a new array with all the elements that returned true based on your condition(s).
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’ :
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; >>).length; // 6
But this can be shortened a lot with ES6 syntax:
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(item => item.status === '0').length; // 6
reduce()
Think of the reduce() method like a Swiss army knife – it’s extremely flexible, and lets you take an array as input and transform it into just about anything. Even better, like filter() , this method returns a new array, leaving the original unchanged.
You can read more about reduce() in this article.
For our purposes, we want to take an array, examine its contents, and produce a number. Here’s a simple way to do that:
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.reduce((counter, obj) => < if (obj.status === '0') counter += 1 return counter; >, 0); // 6
You could simplify further by using ES6 syntax and a ternary operator:
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.reduce((counter, obj) => obj.status === '0' ? counter += 1 : counter, 0); // 6
And even a bit more by using object destructuring:
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.reduce((counter, < status >) => status === '0' ? counter += 1 : counter, 0); // 6
So those are a few ways to go through the elements of an array and count them conditionally. Now get out there and count with confidence!
Array: length
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.
Try it
Value
A nonnegative integer less than 2 32 .
Property attributes of Array: length | |
---|---|
Writable | yes |
Enumerable | no |
Configurable | no |
Description
The value of the length property is a nonnegative integer with a value less than 2 32 .
const listA = [1, 2, 3]; const listB = new Array(6); console.log(listA.length); // 3 console.log(listB.length); // 6 listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length const listC = new Array(-100); // Negative numbers are not allowed // RangeError: Invalid array length
The array object observes the length property, and automatically syncs the length value with the array’s content. This means:
- Setting length to a value smaller than the current length truncates the array — elements beyond the new length are deleted.
- Setting any array index (a nonnegative integer smaller than 2 32 ) beyond the current length extends the array — the length property is increased to reflect the new highest index.
- Setting length to an invalid value (e.g. a negative number or a non-integer) throws a RangeError exception.
When length is set to a bigger value than the current length, the array is extended by adding empty slots, not actual undefined values. Empty slots have some special interactions with array methods; see array methods and empty slots.
const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // set array length to 5 while currently 2. console.log(arr); // [ 1, 2, ] arr.forEach((element) => console.log(element)); // 1 // 2
Examples
Iterating over an array
In the following example, the array numbers is iterated through by looking at the length property. The value in each element is then doubled.
const numbers = [1, 2, 3, 4, 5]; const length = numbers.length; for (let i = 0; i length; i++) numbers[i] *= 2; > // numbers is now [2, 4, 6, 8, 10]
Shortening an array
The following example shortens the array numbers to a length of 3 if the current length is greater than 3.
const numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) numbers.length = 3; > console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 console.log(numbers[3]); // undefined; the extra elements are deleted
Create empty array of fixed length
Setting length to a value greater than the current length creates a sparse array.
const numbers = []; numbers.length = 3; console.log(numbers); // [empty x 3]
Array with non-writable length
The length property is automatically updated by the array when elements are added beyond the current length. If the length property is made non-writable, the array will not be able to update it. This causes an error in strict mode.
"use strict"; const numbers = [1, 2, 3, 4, 5]; Object.defineProperty(numbers, "length", writable: false >); numbers[5] = 6; // TypeError: Cannot assign to read only property 'length' of object '[object Array]' numbers.push(5); // // TypeError: Cannot assign to read only property 'length' of object '[object Array]'
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jun 27, 2023 by MDN contributors.
Your blueprint for a better internet.