Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  1] [ 5]  / answers: 1 / hits: 30915  / 9 Years ago, fri, november 6, 2015, 12:00:00

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).


More From » arrays

 Answers
8

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);

[#64480] Wednesday, November 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;