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).
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.
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.
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.
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);
.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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With