Reputation: 308
I want to find the longest array and get his length.
This is array:
[["667653905", "Johjn", "Smith"], ["500500500", "John", "Smith2", "Another field"], ["12342312", "asd", "asdasd", "fghfgh", "fghfgh"]]
Currently i am using loop but this is very slow solution if i have 50k arrays:
for(var i = 0; i<explode.length; i++) {
console.log(explode[i].length);
}
Upvotes: 0
Views: 76
Reputation: 1810
Just a complement to the answer above. If the array is 50K or more, it may be better to consider moving the code into the backend firstly. In that case, it could be done by java or other low level languages, or even using parallel programming solution. The speed will be increased dramatically.
Upvotes: 3
Reputation: 243
You could only make an assignment (or output) fewer times, to boost it up.
Although I'm not a hundred percent sure the if ()
would actually be faster than other aproach (as the use of reduce()
[don't know it's implementation]), try this implementation with the 50k array:
var max = 0;
var explode = new Array();
explode = [["667653905", "Johjn", "Smith"],
["500500500", "John", "Smith2", "Another field"],
["12342312", "asd", "asdasd", "fghfgh", "fghfgh"]];
var explodeSize = explode.length;
for (var i = 0; i<explodeSize; i++) {
if (max < explode[i].length) {
max = explode[i].length;
}
}
console.log(max);
Upvotes: 0
Reputation: 413720
You can find the longest array with .reduce()
var longest = theArray.reduce(function(lsf, a) {
return !lsf || a.length > lsf.length ? a : lsf;
}, null);
console.log("longest array has " + longest.length + " elements");
Upvotes: 4