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.

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 netflix = ["Stranger Things", "Money Heist", "Loki", "WandaVision"]

let length = netflix.length

console.log(length)

Output

4

It returns 4, which means the array contains four 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 in JavaScript, you can 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. That’s it.

Leave a Comment