Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of the longest array in an array of arrays

Tags:

If you have an array containing an indefinite amount of arrays

ex:

var masterArray = [ [1,2,3,4,5],                     [1,2],                      [1,1,1,1,2,2,2,2,4,4],                     [1,2,3,4,5] ]; 

What is an efficient way to find the index of the longest array in masterArray? (in this example index would be 2).

like image 436
jmancherje Avatar asked Nov 06 '15 23:11

jmancherje


People also ask

How do you find the longest array?

You can iterate over all entries of the outer array using a for loop and compare the length of each of its items to the longest array you have found so far. The following function returns the index of the longest array or -1 if the array is empty. Show activity on this post.

How do you find the index of an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

What is the index of an array?

The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.


2 Answers

One-liner is:

masterArray   .map(a=>a.length)   .indexOf(Math.max(...masterArray.map(a=>a.length))); 

But better to cache masterArray.map(a=>a.length) results.

const lengths = masterArray.map(a=>a.length); lengths.indexOf(Math.max(...lengths)); 

Note, this code still iterate array at least* 3 times(map, max, indexOf separately).

*Spread operator is for readability and can be omitted


For more efficiency you should manual iterate array.

let max = -Infinity; let index = -1; masterArray.forEach(function(a, i){   if (a.length > max) {     max = a.length;     index = i;   } }); 

Reduce method:

masterArray.reduce((maxI,el,i,arr) =>      (el.length>arr[maxI].length) ? i : maxI, 0); 
like image 58
vp_arth Avatar answered Sep 18 '22 18:09

vp_arth


.reduce is the nicest way to do this:

masterArray.reduce(function (pending, cur, index, ar) { ar[ pending ].length > cur.length ? pending : index }, 0); 

Or with ES6:

masterArray.reduce((p, c, i, a) => a[p].length > c.length ? p : i, 0); 
like image 29
Downgoat Avatar answered Sep 19 '22 18:09

Downgoat