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.

2
  • Have you tried something? I mean, do you have a sample code that performs merge sort? Commented Dec 25, 2021 at 22:11
  • stackoverflow.com/questions/1129216/… Commented Dec 27, 2021 at 18:18

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

8 Comments

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 test.sort((a, b) => b.numbers.length - a.numbers.length).map(o => o.name)
It does not work with arrays with other names than a, b and c...
@EnTil Please post an example of such array
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']
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.