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!
var result = [], mlength = arr[0].length; for(var i = 0, l = arr.length; i < l; i++) { if(arr[i].length < mlength) break; result.push(arr[i]); }
. That said, there might be still other, better, ways. – Felix Kling Oct 21 '11 at 10:28