0

I would like to understand how to use merge sort to sort arrays based on the number of values in each array.

let test = [
{
name: "a",
numbers: [1,2]
},{
name: "b",
numbers: [1,2,3]
},{
name: "c",
numbers: [5]

The 'a' has 2 numbers, the 'b' has 3 numbers and the 'c' has 1 number. So it should be sorte as follows, from high to low: b, a, c.

EnTil
  • 11
  • 2

1 Answers1

5

Just use the array sort with a compare function.
The function should substract the lengths of the numbers property of objects.
More info: Array.sort() on MDN

test.sort((a, b) => b.numbers.length - a.numbers.length)
Nikita Skrebets
  • 1,518
  • 2
  • 13
  • 19
  • How about if it was like this: let test = [ { name: "abc", numbers: [1,2] },{ name: "def", numbers: [1,2,3] },{ name: "ghi", numbers: [5]} And it should be from high to low: def, abc, ghi...? – EnTil Dec 25 '21 at 21:20
  • @EnTil `test.sort((a, b) => b.numbers.length - a.numbers.length).map(o => o.name)` – Nikita Skrebets Dec 25 '21 at 21:24
  • It does not work with arrays with other names than a, b and c... – EnTil Dec 25 '21 at 21:41
  • @EnTil Please post an example of such array – Nikita Skrebets Dec 25 '21 at 21:42
  • Because this works `[ { name: "abc", numbers: [1,2] },{ name: "def", numbers: [1,2,3] },{ name: "ghi", numbers: [5]}].sort((a, b) => b.numbers.length - a.numbers.length).map(o => o.name)`, It gives `['def', 'abc', 'ghi']` – Nikita Skrebets Dec 25 '21 at 21:43
  • Please also explain *what* this is doing, for future questioners landing on this question. – Roy Dec 27 '21 at 14:29
  • @Roy updated. Though it's hard to explain more than giving a link to the docs. Does this look good enough? And second question, why is it better to use (lets call it) block code than inline code (3 backticks instead of 1)? – Nikita Skrebets Dec 27 '21 at 18:10
  • One backtick is mostly used for inline code elements, with three backticks before and after on newline, you can even specify the code language. See also https://meta.stackoverflow.com/a/251362 – Roy Dec 27 '21 at 18:43