1

I have the following array to sort.

const input = ["12 - Blue, Red, Orange, Purple", 
"16 - White, Black, Yellow, Blue, Pink",
"14 -  Yellow, Brown, Grey, Maroon, Green",
"20 - Red, Black, Yellow, Peach, Aqua",
"7 - White, Cream, Grey, Green, Magenta" ]

The aim is to sort rows in ascending order like 7th row, then 12th, 14th, 16th finally 20th. Here is what I tried but not working

const input = [
  "12 - Blue, Red, Orange, Purple",
  "16 - White, Black, Yellow, Blue, Pink",
  "14 -  Yellow, Brown, Grey, Maroon, Green",
  "20 - Red, Black, Yellow, Peach, Aqua",
  "7 - White, Cream, Grey, Green, Magenta"
]

var x = input.sort(function(a, b) {
  return a[0] > b[0] ? 1 : -1;
});

console.log(x)

How to sort such a complex array in ascending order?

Andreas
  • 21,535
  • 7
  • 47
  • 56
pratik jaiswal
  • 1,855
  • 9
  • 27
  • 59

1 Answers1

4

You need to take the integer values and sort by the delta of it.

const
    input = ["12 - Blue, Red, Orange, Purple",
        "16 - White, Black, Yellow, Blue, Pink",
        "14 -  Yellow, Brown, Grey, Maroon, Green",
        "20 - Red, Black, Yellow, Peach, Aqua",
        "7 - White, Cream, Grey, Green, Magenta"
    ];

input.sort(function(a, b) {
    return parseInt(a, 10) - parseInt(b, 10);
});

console.log(input);

With sorted colors.

const
    input = ["12 - Blue, Red, Orange, Purple",
        "16 - White, Black, Yellow, Blue, Pink",
        "14 -  Yellow, Brown, Grey, Maroon, Green",
        "20 - Red, Black, Yellow, Peach, Aqua",
        "7 - White, Cream, Grey, Green, Magenta"
    ],
    sorted = input
        .map(s => {
            const [number, colors] = s.split(' - ');
            return [
                number,
                colors
                    .split(/,\s*/)
                    .sort((a, b) => a.localeCompare(b))
                    .join(', ')
            ].join(' - ');
        })
       .sort((a, b) => parseInt(a, 10) - parseInt(b, 10));

console.log(sorted);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392