I have a nested array like this var input = [2, 4, 2, 6, 1, [4, 2, 1], [0, 2, 1, 6, [2, 1], [1]], [1], 5];
and the output should be sorted in such a way that, all the numbers should come first in its ascending order and if the array contains subarrays it should come in the order of its length. That is, subarray with length 1 should come first, subarray with length 2 come second etc. Also if there are numbers in it, it should be sorted ascending.
var output = [1, 2, 2, 4, 5, 6, [1], [1, 2, 4], [0, 1, 2, 6, [1], [1, 2]]];
Below is my implementation but it sorts only one level deep. How to call it recursively?
function sortArray(arr) {
return [...arr]
.sort((a, b) => {
if (Array.isArray(a) && Array.isArray(b)) return a.length - b.length;
else if (Array.isArray(a) || Array.isArray(b)) return 1;
else return a - b;
});
}
return 1
even ifArray.isArray(b)
- it shouldreturn -1
then.a
is a number andb
is an array, the number should come first - so you need to return a negative value.