JavaScript - array undefined element count


We are required to write a JavaScript function that takes in an array of elements. The array of elements might contain some undefined values as well.

Our function should count the length of the array and the count should only contain the count of defined elements.

Example

The code for this will be −

const arr = [12, undefined, "blabla", ,true, 44];
const countDefined = (arr = []) => {
   let filtered;
   filtered = arr.filter(el => {
      return el !== undefined;
   });
   const { length } = filtered;
   return length;
};
console.log(countDefined(arr));

Output

And the output in the console will be −

4

Updated on: 23-Nov-2020

560 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements