Categories:Viewed: 72 - Published at: 6 months ago

Introduction

An array is used to store an ordered collection of values. These values could be a combination of either the same data type or numerous data types - integers, floats, strings, boolean, objects, and lots more. Getting the number of elements in an array with JavaScript is a common operation when consuming data or working with APIs in JavaScript. This can be accomplished either by utilizing the length property or iterating through an array and counting the elements.

In this article, we will learn how to get the number of elements in an array with JavaScript and much more - how to count unique elements and how to count elements of an array based on certain conditions.

Using the Built-in length Property

The standard way to get the total number of elements in an array is to use the built-in length property:

let myArray = [99, 101.5, "John Doe", true, { age: 44 }];
let total = myArray.length;
console.log(total); // Output: 5

// Alternatevly:
let total = [99, 101.5, "John Doe", true, { age: 44 }].length;
console.log(total); // Output: 5
Note: length refers to a cached value of the length of the array, computed when the array is being created. Therefore, you don't iterate the array by calling length explicitly, nor implicitly. This ensures that length scales up to an arbitrary level and doesn't impact the performance of your application, such as the impact you'd feel when manually looping through.
        <h3 id="usingloopsinjavascript">Using Loops in JavaScript</h3>

JavaScript loops can also be used to count the length of an array by iterating through the array and incrementing the counter variable by one for each element in the array. This is mostly used when you want to perform certain operations on the elements themselves or on a particular element since we are iterating through all the elements in the array.

Note: This approach harder compared to the previously described length property, though, it's pretty simple in and of itself. It's worth noting that longer arrays take longer to iterate through, while length returns the cached value with a constant lookup time.
        <h4 id="forloop"><em>for</em> Loop</h4>
let myArray = [99, 101.5, "John Doe", true, { age: 44 }];

// Counter variable
let total = 0;

for (let i = 0; i < myArray.length; i++) {
    total++;
}

console.log(total); // Output: 5

for...in Loop

let myArray = [99, 101.5, "John Doe", true, { age: 44 }];

let total = 0;
for (i in myArray) {
    total++;
}

console.log(total); // Output: 5

Get the Number of Unique Elements in an Array

Arrays in JavaScript can have multiple elements of different data types and these elements could include some duplicates. If we want to get the number of unique elements we can use the Set()constructor. It creates a set out of the array passed as its argument. Therefore it helps us remove duplicates and returns only unique elements (a set is a collection of unique elements). When duplicates are removed, we can use the length property to get the number of unique elements.

Hint: If you want to learn more about how to remove duplicates from an array in JavaScript, you should read How to Remove Duplicates From an Array in JavaScript!
        For example, suppose we have an array of names that has a total of 7 elements, among which 6 are unique. We can  get the unique elements first and then make use of the length property to get the length:
let names = ["John", "Dan", "Jane", "Sam", "Alisa", "John", "Pete"];
let uniqueNames = [...new Set(names)];
let totalPeople = uniqueNames.length;

console.log(totalPeople); // Output: 6
Note: This can also work with loops. After we get the unique elements stored in a new array, all we have to do is to loop it through and count elements as we've done earlier.
        <h3 id="whatifanarraycontainsotherarraysaselements">What If an Array Contains Other Arrays as Elements?</h3>

As we've stated before, arrays in JavaScript can contain elements of many data types - including an Array data type. This may be a bit confusing at first, but when you get a grasp on how length property counts those subarrays, you are going to be able to handle this situation without any problems. The first method that probably goes to mind is to use the length property:

let myArray = [["John", "Pete"], [90, 2], [], [34, 45, 2], [9,4], "John Doe", true, [19]];
let total = myArray.length;

console.log(total); // Output: 8

Note how the length property treats each subarray as one element. It doesn't consider the contents of subarrays - no matter if it's empty or it has a large number of elements, it is counted as one element of the original array (in this case, myArray).

Get the Number of Elements in an Array Containing Other Arrays

Let's now learn how to count the number of all elements in an array - including those elements inside subarray elements. We can use a couple of approaches, such as a for loop or a for...in, etc. We'll first initialize the totalLength to 0, then create a function (myLength()) which will be used to loop through the array and count the number of its elements. First of all, we need to loop through the original array and consider each of its elements. If the element is not an array, we'll just increase the totalLength by 1. On the other hand, if the current element is an array (subarray of the original array), we'll recursively call the myLength method to calculate the number of its elements:

let myArray = [["John", "Pete"], [90, 2], [], [34, 45, 2], [9,4], "John Doe", true, [19]];

let totalLength = 0;
const myLength = (array) => {
    // For each element of the `myArray`
    for (let i in array) {
        // If the element is an array
        // recursively call `myLength` to calculate
        // the length of the current element
        // Otherwise, just increment the `totalLength`
        if (Array.isArray(array[i])) {
            myLength(array[i]);
        } else {
            totalLength++;
        }
    }
};

myLength(myArray);
console.log(totalLength); // Output: 12

Alternatively, you can simply call the flat() method on myArray, which flattens it by recursively concatenating all of the elements into a 1D array, and then call length on the new array:

console.log(myArray.flat().length) // Output: 12

Count Based on Conditions

Like we've mentioned earlier, we can also count the number of elements in an array based on certain conditions. For example, suppose we have an array of students which consists of objects, each object containing students name and score:

const students = [
    { name: "John Doe", score: 70 },
    { name: "Jane Doe", score: 40 },
    { name: "Sarah Jane", score: 33 },
    { name: "John Tough", score: 84 },
    { name: "Jabes Tough", score: 64 }
];

We can count the total number of students that score above 60, by looping through each element and counting ones that passed the predefined condition:

let total = 0;

students.forEach((student) => {
    if (student.score >= 60) {
        total++;
    }
});

console.log(total); // Output: 3

This would also work for other iteration methods like the for loop:

let total = 0;

for (let i = 0; i < students.length; i++) {
    if (students[i].score >= 60) {
        total++;
    }
}

console.log(total); // Output: 3

Conclusion

In this article, we learned how to get the number of elements in an array and we saw various scenarios that could warrant us getting the length of an array and how we could achieve each of them.

Reference: stackabuse.com

TAGS :