I have an error:
"Uncaught (in promise) TypeError: _post1 $ _this3 $ selecte.localeCompare"
I understand post1 gets a number as an argument, but how can I compare "localeCompare" numbers?
return [...this.posts].sort((post1, post2) => post1[this.selectedSort]?.localeCompare(post2[this.selectedSort]));
You don't have to use localeCompare, with numbers you can just use sort((a, b) => a.x - b.x) if you have an array of objects with a number property you want to use to sort.
For example
const data = [{age: 12}, {age: 7}, {age: 18}];
const result = data.sort((a, b) => a.age - b.age);
console.log(result);
I temporarily fixed the problem with the if else operator but leave the issue open as I want to optimize the feature in the future
if(this.selectedSort == 'id'){
return [...this.posts].sort((post1, post2) => post1[this.selectedSort] - post2[this.selectedSort]);
}
else{
return [...this.posts].sort((post1, post2) => post1[this.selectedSort]?.localeCompare(post2[this.selectedSort]));
}
It worked for me !!!
return [...this.posts].sort((post1, post2) => String(post1[this.selectedSort])?.localeCompare(String(post2[this.selectedSort]), 'en', {numeric: true}));