I’m sitting over the following array-problem:
- I have four arrays 1,2,3,4
- each can contain any number of elements
- I’m looking for the array(s) with the highest number of elements (and its 2nd to last element)
I’m using this:
var arr = [],
$panels = $(':jqmData(hash="history")'),
$panels.each(function(index) {
//data("stack") contains the array
arr.push($(this).data("stack"));
});
arr.sort(function(a,b){return b.length - a.length});
console.log( arr[0] );
So if the arrays look like this:
[a,b,c] [d,e] [f,g,h,i] [k,l] console says [ [f,g,h,i] ]
OK, but if two arrays have the same highest length, like so:
[a,b,c,d] [d,e] [f,g,h,i] [k,l] I don’t get [ [a,b,c,d] [f,g,h,i] ]
because arr[0] will only return the first array again.
I’m clueless…
Is there a way to give me the array or arrays with the highest number of elements and their 2nd-to-last respective element?
Thanks!
Use this code:
What happens?
var data = ...The array is retrieved.if(data.length > longestLen)– Comparing the length of the current array to the known longest length.If the new array has a greater size, replace
longestby a new array consisting of elementdata.Update
longestLento the length of the current longest array.else if(data.length == longestLen) longest.push(data)– If the current array has the same length as the longest array, push the current array in the existing arraylongest.