Reputation: 660
I have four arrays A,B.C, and D. For example:
length of A is 1
length of b is 4
length of C is 1
length of D is 2.
var a = [1];
var b = [2,3,4,5];
var c = [6];
var d = [7,8];
I want to concat those four arrays based on the larger length of the arrays, so the arrays will be in order: b
,d
,a
,c
:
Expected result:
[2,3,4,5,7,8,1,6]
[2,3,4,5,1,6,7,8] //also valid, a and c are same length, so can be sorted this way too.
How can I find the larger to lower arrays and concat them from larger to smaller in JavaScript?
Upvotes: 0
Views: 134
Reputation: 16020
It's simple enough using sort
and concat
:
Array.prototype.concat.apply([], [a, b, c, d].sort(function (a, b) {
return b.length - a.length;
}));
Array.prototype.concat.apply
is used to join the child arrays together.
Upvotes: 5
Reputation: 12561
Mine's more verbose but still seems to work; the idea in all first 3 answers is to put the arrays into an additional array, then do a custom sort of the arrays based on their length. A good if somewhat dated reference is at: http://www.javascriptkit.com/javatutors/arraysort.shtml
var arrays = [a, b, c, d];
var concatentation = [];
arrays.sort(function(x, y) {
return y.length - x.length;
});
for (var i=0, n=arrays.length; i<n; i++) {
concatentation = concatentation.concat(arrays[i]);
}
console.log(concatentation); //[2, 3, 4, 5, 7, 8, 1, 6]
Upvotes: 2
Reputation: 12431
You could do this quite neatly with underscore:
_.sortBy([a,b,c,d], function(num) {
return num.length;
}).reverse().join(',').split(',');
Upvotes: 4