0๐
โ
You are comparing strings instead of numbers. String 10
, 11
, 12
are lower than 2
or 3
. Use parseInt
to convert the string before comparing.
getAvailableFloors() {
const set = new Set();
const sorted = this.offices.sort((a, b) => {
if (parseInt(a.acf.floor) > parseInt(b.acf.floor)) {
return 1;
}
if (parseInt(a.acf.floor) < parseInt(b.acf.floor)) {
return -1;
}
return 0;
});
sorted.forEach((office) => {
set.add(office.acf.floor);
});
return set;
},
0๐
You would need to cast your floors to numbers using Number('3')
for example. This will make the comparisons between numbers and not between strings.
When you are comparing strings you will get alphabetical soring (lexicographic ordering) in which for example 10 < 2
.
Here is the fixed sort function:
const sorted = this.offices.sort((a, b) => {
const floorA = Number(a.acf.floor);
const floorB = Number(b.acf.floor);
if (floorA > floorB) {
return 1;
}
if (floorA < floorB) {
return -1;
}
return 0;
});
To read more about type casting see here: https://developer.mozilla.org/en-US/docs/Glossary/Type_Conversion
Source:stackexchange.com