Reputation: 11
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.
Upvotes: 0
Views: 77
Reputation: 1538
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)
Upvotes: 5