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?

2
  • input.sort((a,b)=>{ return parseInt((a.split('-')[0]).trim()) - parseInt((b.split('-')[0]).trim()) }) - assuming your format(<integer> - <string>) will not change. Commented Sep 15, 2020 at 9:14
  • this does not look complex in my opinion Commented Sep 15, 2020 at 9:14

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

4 Comments

is the 10 required? i tried it without and it works aswell
Thank you. How to sort color names alphabetically after sorting of numbers?
in this case, you need to iterate again and separate the items and sort the items.
Sorry, but can you add to your code? Please

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.