0

Evaluating 2 extremely simple arrays, one sorts ok and the other does not:

var qtr = ['zzqtr_1_2020','zzqtr_2_2020','zzqtr_3_2019','zzqtr_4_2019'];
qtr.sort();
// qtr is now zzqtr_1_2020, zzqtr_2_2020, zzqtr_3_2019, zzqtr_4_2019 (no change)

var fruits = ["a_1_Banana", "a_2_Orange", "a_1_Apple", "a_1_Mango"];  
fruits.sort();
// fruits is now  a_1_Apple, a_1_Banana, a_1_Mango, a_2_Orange (SORTED!)

What I cannot figure out is why the qtr array will not be sort properly?

5
  • 2
    It is sorting, but it's already in sorted order. What do you expect to be different? Commented Apr 30, 2020 at 17:47
  • What was your expected result from "qtr array" sort? Commented Apr 30, 2020 at 17:48
  • I wonder if he's expecting it to be sorted as a date, so that the 2019 items should go before 2020. Commented Apr 30, 2020 at 17:49
  • if you like to get the data sorted by date, you could consider to use strings which have the year in front of the month, like an ISO 8601 date string. this is sortable, despite of the same prefix. Commented Apr 30, 2020 at 17:52
  • @NinaScholz Also need 2-digit months, otherwise 12 will sort before 3 Commented Apr 30, 2020 at 17:54

4 Answers 4

2

Because the array is already sorted. Your difference is made by the id after "zzqtr_". And the elements are already sorted.

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

Comments

0

The array is already sorted. The string after "zzqtr_" are in increasing order (ie: from 1 to 4). So, if you did something like this:

var qtr = ['zzqtr_3_2020','zzqtr_1_2020','zzqtr_4_2019','zzqtr_1_2019'];
qtr.sort();
var x = qtr.toString();

now, you will see a change :)

Comments

0

Array.prototype.sort() is comparing UTF-16 sequences, so zzqtr_1, zzqtr_2, zzqtr_3, zzqtr_4 is already sorted according to that, the last bit of text (the year) is not relevant there.

I assume you want to sort by year, so in that case, you need to implement a custom sorting function:

const qtr = ['zzqtr_1_2020','zzqtr_2_2020','zzqtr_3_2019','zzqtr_4_2019'];

qtr.sort((a, b) => {
  const aParts = a.split('_');
  const bParts = b.split('_');
  
  return (parseInt(aParts[2]) - parseInt(bParts[2])) || a.localeCompare(b);
});

console.log(qtr.join(', '));

Comments

0

Array.prototype.sort() works by comparing UTF-16 code points, which can lead to unexpected results sometimes.

Instead, consider using String.prototype.localeCompare() function, which compares two strings, based on the alphabets of the locale and not UTF-16 code points

Comments

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.