JavaScript Array Length: How to Count Elements in Array

To count elements of an array in JavaScript, you can use the length property. The length property sets or returns the number of elements in an array.

The value of a length property is the integer with a positive sign and a value less than 2 to the 32nd power.

Diagram of How to Count Elements in Array

Process Diagram of Counting Elements in an Array

Syntax

array.length

To set the length of the array, use the array.length=number syntax.

Return Value

The length property returns a Number, representing the number of elements in the array object.

Example

const data = [11, 21, 46, 19, 10]

let len = data.length

console.log(len)

Output

5

It returns 5, which means the array contains five elements. The length property of an object, an instance of type Array, sets or returns the number of elements in that array.

How to count certain elements in an array

To count certain elements in the array, use the “filter()” function with the length property.

const arr = [11, 21, 19, 21, 46]

const elementToCount = 21; 

let count = arr.filter(x => x == elementToCount).length

console.log(count)

Output

2

In this example, the “filter()” method creates a new array that only contains elements equal to elementToCount.

Then, we used the filtered array’s length property to get the desired element’s count.

You can generalize this to a function to make it reusable:

function countOccurrences(arr, elementToCount) {
   return arr.filter(item => item === elementToCount).length;
}

const arr = [1, 2, 3, 2, 1, 2, 3, 1, 1, 1, 2, 3, 3, 3];
console.log(countOccurrences(arr, 1)); // Output: 6
console.log(countOccurrences(arr, 2)); // Output: 4
console.log(countOccurrences(arr, 3)); // Output: 5

This function takes an array arr and an element elementToCount and returns the count of that element in the array.

Summary

Task Method Efficiency Reliability
Count the total elements in the array Use the length property: let count = array.length; Highly efficient. Highly reliable.
Count occurrences of each element in the array Use techniques like for-loop, reduce, or Map/Object to iterate over the array and tally each occurrence. Varies by technique. Varies by technique.

That’s it!