I have the following arrays:
/
I need to sort the arrays by their length.
How to find out which one is the largest, the second largest, the third largest, and the least array?
For example, I have the following dummy function, that can get us the second largest array:
/
What is the above dummy function algorithm?
Thank you in advance
I have the following arrays:
http://jsfiddle/3NZsK/
I need to sort the arrays by their length.
How to find out which one is the largest, the second largest, the third largest, and the least array?
For example, I have the following dummy function, that can get us the second largest array:
http://jsfiddle/WPRYf/
What is the above dummy function algorithm?
Thank you in advance
Share Improve this question edited Jun 26, 2012 at 12:49 Bayu asked Jun 26, 2012 at 11:30 BayuBayu 4672 gold badges10 silver badges19 bronze badges 15- sorry, what? you mean you want to sort the arrays by their length? – gexicide Commented Jun 26, 2012 at 11:32
- I want to find out which one is the largest, the second largest, the third largest and the smallest in quantity. I need to assign them into above variables (please see my explanation) – Bayu Commented Jun 26, 2012 at 11:37
- I think when @gexicide said "What?" he meant that your explanation doesn't make a lot of sense, and he would like you to clarify it. – phenomnomnominal Commented Jun 26, 2012 at 11:40
- Ok. Yes, I want to sort the arrays by their length. How can I do that? – Bayu Commented Jun 26, 2012 at 11:43
- 1 In that case the second fiddle example is wrong. – Angel Commented Jun 26, 2012 at 11:50
2 Answers
Reset to default 12var
a = ["a", "a"];
b = ["b", "b", "b", "b"],
c = ["c", "c", "c"],
d = ["d"],
container = [a, b, c, d];
container.sort(function (a, b) {
return b.length - a.length;
});
console.log(container);
container
will be sorted from longest (most elements) to shortest (least number of elements). Access it as:
container[0] // longest
container[1] // 2nd longest
// ...
http://jsfiddle/pSRVq/
You can find the length of the array using the length method and then sort these according to their values to find the largest, second largest array.