Javascript count arrays in array

JavaScript: Number of arrays inside an array

Write a JavaScript program to count the number of arrays inside a given array.

Sample Solution:

JavaScript Code-1:

function test(arr_nums)< return arr_nums.filter(n=>Array.isArray(n)).length; > arr_nums = [2,8,[6],3,3,5,3,4,[5,4]] console.log("Number of arrays inside the said array: "+test(arr_nums)); arr_nums = [2,8,[6,3,3],[4],5,[3,4,[5,4]]] console.log("Number of arrays inside the said array: "+test(arr_nums)); 
Number of arrays inside the said array: 2 Number of arrays inside the said array: 3

JavaScript array flowchart: Number of arrays inside an array.

JavaScript Code-2:

function test(arr_nums) < return arr_nums.filter(n=>n.length).length; > arr_nums = [2,8,[6],3,3,5,3,4,[5,4]] console.log("Number of arrays inside the said array: "+test(arr_nums)); arr_nums = [2,8,[6,3,3],[4],5,[3,4,[5,4]]] console.log("Number of arrays inside the said array: "+test(arr_nums)); 
Number of arrays inside the said array: 2 Number of arrays inside the said array: 3

JavaScript array flowchart: Number of arrays inside an array.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

How do I loop through or enumerate a JavaScript object?

You can use the for-in loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn’t come from the prototype.

var p = < "p1": "value1", "p2": "value2", "p3": "value3" >; for (var key in p) < if (p.hasOwnProperty(key)) < console.log(key + " ->" + pJavascript count arrays in array); > >

For-of with Object.keys() alternative:

var p = < 0: "value1", "b": "value2", key: "value3" >; for (var key of Object.keys(p)) < console.log(key + " ->" + pJavascript count arrays in array) >

Notice the use of for-of instead of for-in, if not used it will return undefined on named properties, and Object.keys() ensures the use of only the object’s own properties without the whole prototype-chain properties

Using the new Object.entries() method:

Note: This method is not supported natively by Internet Explorer. You may consider using a Polyfill for older browsers.

const p = < "p1": "value1", "p2": "value2", "p3": "value3" >; for (let Javascript count arrays in array of Object.entries(p)) < console.log(`$: $`); >
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

How to Count Objects in an Array

How to Count Objects in an Array

Knowing how to quickly iterate through an array and count objects is deceptively simple. The length() method will tell you the total number of values in the array, but what if you only want to count those values based on certain conditions?

For example, imagine you have an array like this:

And you only want to count the number of objects with status set to ‘0’ .

Like with just about everything in programming, there are a number of ways to do this. We’ll go through a few of the common methods below.

Use a for loop

Probably the easiest way would be to declare a counter variable, loop through the array, and iterate counter only if status is equal to ‘0’ :

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; let counter = 0; for (let i = 0; i < storage.length; i++) < if (storage[i].status === '0') counter++; >console.log(counter); // 6

You could simplify this a bit by using a for. of loop:

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; let counter = 0; for (const obj of storage) < if (obj.status === '0') counter++; >console.log(counter); // 6

Also, you could create a function to do the same thing if you have other arrays of objects to count conditionally:

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; function statusCounter(inputs) < let counter = 0; for (const input of inputs) < if (input.status === '0') counter += 1; >return counter; > statusCounter(storage); // 6

Use array methods

JavaScript includes a bunch of helpful methods when working with arrays. Each one can be chained to an array and passed different parameters to work with while iterating through the elements in the array.

The two we’ll look at are filter() and reduce() .

filter()

The filter method does just that – it iterates through each element in the array and filters out all elements that don’t meet the condition(s) you provide. It then returns a new array with all the elements that returned true based on your condition(s).

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; const count = storage.filter(function(item) < if (item.status === 0) < return true; >else < return false; >>); /* [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >] */

Now that you’ve filtered out the object with status: ‘1’ , just call the length() method on the new array to get the total count of objects with status: ‘1’ :

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; const count = storage.filter(function(item) < if (item.status === 0) < return true; >else < return false; >>).length; // 6

But this can be shortened a lot with ES6 syntax:

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; const count = storage.filter(item => item.status === '0').length; // 6

reduce()

Think of the reduce() method like a Swiss army knife – it’s extremely flexible, and lets you take an array as input and transform it into just about anything. Even better, like filter() , this method returns a new array, leaving the original unchanged.

You can read more about reduce() in this article.

For our purposes, we want to take an array, examine its contents, and produce a number. Here’s a simple way to do that:

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; const count = storage.reduce((counter, obj) => < if (obj.status === '0') counter += 1 return counter; >, 0); // 6

You could simplify further by using ES6 syntax and a ternary operator:

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; const count = storage.reduce((counter, obj) => obj.status === '0' ? counter += 1 : counter, 0); // 6

And even a bit more by using object destructuring:

const storage = [ < data: '1', status: '0' >, < data: '2', status: '0' >, < data: '3', status: '0' >, < data: '4', status: '0' >, < data: '5', status: '0' >, < data: '6', status: '0' >, < data: '7', status: '1' >, ]; const count = storage.reduce((counter, < status >) => status === '0' ? counter += 1 : counter, 0); // 6

So those are a few ways to go through the elements of an array and count them conditionally. Now get out there and count with confidence!

Источник

Javascript count arrays in array

Last updated: Jan 8, 2023
Reading time · 4 min

banner

# Count Elements in an Array that match a Condition using JS

To count the elements in an array that match a condition:

  1. Use the filter() method to iterate over the array.
  2. Check if each element meets the condition.
  3. Access the length property on the array to get the number of elements that meet the condition.
Copied!
const arr = [1, 11, 2, 12, 3, 13]; const count = arr.filter(element => if (element > 10) return true; > return false; >).length; console.log(count); // 👉️ 3

The function we passed to the Array.filter method gets called with each element in the array.

The filter() method returns a new array that only contains the elements that meet the condition.

Copied!
const arr = [1, 11, 2, 12, 3, 13]; // 👇️ [ 11, 12, 13 ] console.log(arr.filter(element => element > 10));

On each iteration, we check if the current array element is greater than 10 .

If the condition is met, we return true , otherwise, we return false .

We can access the length property on the filtered array to get the count of the elements that meet the condition.

Copied!
const arr = [1, 11, 2, 12, 3, 13]; // 👇️ 3 console.log(arr.filter(element => element > 10).length);

You can also shorten the function by returning the comparison instead of returning true or false .

Copied!
const arr = [1, 11, 2, 12, 3, 13]; const count = arr.filter(element => element > 10).length; console.log(count); // 👉️ 3

We directly check if each element is greater than 10 and return the result instead of explicitly returning true and false .

An alternative approach is to use the Array.reduce method.

# Count Elements in an Array that match a Condition using reduce()

This is a three-step process:

  1. Use the reduce() method to iterate over the array.
  2. If the element matches the condition return the accumulator value + 1.
  3. If the condition is not matched, return the accumulator .
Copied!
const arr = [1, 11, 2, 12, 3, 13]; const count = arr.reduce((accumulator, element) => if (element > 10) return accumulator + 1; > return accumulator; >, 0); console.log(count); // 👉️ 3

The function we passed to the Array.reduce method gets called for each element in the array.

We initialized the accumulator variable to a 0 because that’s what we passed as the second argument to the reduce() method.

On each iteration, we check if the current element is greater than 10 .

If the condition is met, we return the accumulator value + 1, otherwise, we return the accumulator .

The value we return from the callback function gets passed as the accumulator for the next iteration.

After the last iteration, the reduce method returns the count of the array elements that match the condition.

# Count Elements in an Array that match a Condition using forEach()

This is a four-step process:

  1. Declare a count variable and initialize it to 0 .
  2. Use the Array.forEach() method to iterate over the array.
  3. Check if each element meets the condition.
  4. Increment the count variable if the condition is met.
Copied!
const arr = [1, 11, 2, 12, 3, 13]; let count = 0; arr.forEach(element => if (element > 10) count += 1; > >); console.log(count); // 👉️ 3

The function we passed to the Array.forEach method gets called with each element in the array.

The forEach() method returns undefined , so we have to perform some kind of mutation to persist the state.

On each iteration, we check if the current array element is greater than 10 .

If the condition is met, we increment the count variable by 1 .

Notice that we used let to declare the count variable. Variables declared using const cannot be reassigned.

# Count Elements in an Array that match a Condition using for. of

You can also use a for. of loop to count the elements that match a condition.

Copied!
const arr = [1, 11, 2, 12, 3, 13]; let count = 0; for (const element of arr) if (element > 10) count += 1; > > console.log(count); // 👉️ 3

The for. of statement is used to loop over iterable objects like arrays, strings, Map , Set and NodeList objects and generators .

On each iteration, we check if the current element meets the condition and if it does, we increment the count variable by 1 .

# Count Elements in an Array that match a Condition using a for loop

You can also use a basic for loop to count the elements in an array that meet a condition.

Copied!
const arr = [1, 11, 2, 12, 3, 13]; let count = 0; for (let index = 0; index arr.length; index++) if (arr[index] > 10) count += 1; > > console.log(count); // 👉️ 3

The for loop is quite verbose and requires us to make use of the index to access the current array element.

Which approach you pick is a matter of personal preference. I’d use the Array.forEach() method because I find it more direct.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Стиллер на python это
Оцените статью