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

  • Using the array.filter() Method

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.

<html>
   <head>
   </head>
   <body>
      <h2> Count JavaScript array objects. </h2>
      <h4> Counting total number of array objects in array using the <i> for loop. </i> </h4>
      <p id = "objects"> </p>
      <script>
         let objects = document.getElementById("objects");
         var objectsLen = 0;
         
        // array of objects and ohter elements
        var myArr = [{ "id": 1, "int": 10 }, { "id": 2, "int": 20 }, { "id": 3, "int": 30 }, "TutorialsPoint", 20, "Hello"];
        for (let i = 0; i < myArr.length; i++) {
           // checking the type of the object.
           if ( myArr[i] instanceof Object ) {
               objectsLen++;
           }
       }
       objects.innerHTML += "Original Array: " + JSON.stringify(myArr)+"<br>";
       objects.innerHTML += "<br>Total number of objects: " +  objectsLen ;
   </script>
   </body>
</html>

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.

<html>
   <body>
   <h2> Count JavaScript array objects. </h2>
   <h4> Counting total number of array objects in array using the <i> arrays.filter() </i> method. </h4>
   <p id = "objects"> </p>
   <script>
      let objects = document.getElementById("objects");
      
      // array of objects and ohter elements      
      var array = ["TutorialsPoint", 20, { "id": 2, "int": 20 }, { "id": 3, "int": 30 }, "Hello"];
      let allObject = array.filter((val) => {
         if ( typeof val == 'object' ) {
            return true;
         } else {
            return false;
         }
      });
       let objectsLen = allObject.length;
       objects.innerHTML += "Original String: " + JSON.stringify(array) + " <br> ";
       objects.innerHTML += "<br>Total Objects in the array: "  + objectsLen 
   </script>
   </body>
</html>

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.

Updated on: 31-Oct-2023

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements