3

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;
    });
}
4
  • There's a mistake in your comparison function where it does return 1 even if Array.isArray(b) - it should return -1 then.
    – Bergi
    Commented Nov 30, 2019 at 18:31
  • @Bergi, when a is an array and b, is number or vice versa, the array should come last. Commented Nov 30, 2019 at 18:36
  • 3
    That's what I'm saying. When a is a number and b is an array, the number should come first - so you need to return a negative value.
    – Bergi
    Commented Nov 30, 2019 at 18:42
  • @Bergi got it. Thanks. Commented Dec 1, 2019 at 6:27

2 Answers 2

5

Use Array.map() on the array before you sort it, and if the item is an array call sortArr:

function sortArray(arr) {
  return arr
    .map(a => Array.isArray(a) ? sortArray(a) : a)
    .sort((a, b) => {
      if (Array.isArray(a) && Array.isArray(b)) return a.length - b.length;
      else if (Array.isArray(a)) return 1;
      else if (Array.isArray(b)) return -1;
      else return a - b;
    });
}

const input = [2, 4, 2, 6, 1, [4, 2, 1], [0, 2, 1, 6, [2, 1], [1]], [1], 5];

const result = sortArray(input);

console.log(result);

3

You could do this by creating recursive function using forEach loop and also using sort method.

var input = [2, 4, 2, 6, 1, [4, 2, 1], [0, 2, 1, 6, [2, 1], [1]], [1], 5];

function deepSort(data) {
  data.sort((a, b) => !Array.isArray(b) - !Array.isArray(a) || a - b || a.length - b.length)
  data.forEach(e => Array.isArray(e) && deepSort(e))
}


deepSort(input);
console.log(JSON.stringify(input));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.