Reputation: 153
I have two functions that look like this:
const compare = (direction: string) => {
const alphabetize = (a, b) => {
if (direction === "alpha") {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
} else if (direction === "reverseAlpha") {
if (a.name > b.name) {
return -1;
}
if (a.name < b.name) {
return 1;
}
}
return 0;
};
};
const sortAlphabetically = () => {
setState(state => ({
...state,
items: items.sort(compare("alpha"))
}));
};
I need to be able to pass a string into the compare
function somehow, that tells it which way to sort the letters (alphabetically, or reverse alphabetically).
But this method doesn't work, because alphabetize
is never called this way. What am I missing?
Thank you!
Upvotes: 1
Views: 177
Reputation: 6390
You can try this short solution:
const data = ['zoo', 'river', 'dimond', 'man', 'football', 'hot'];
// Keep the data array for another sort, as sort changes the original array. You can perform this to the `data` array too. This also gives you the same result.
const clone = [...data];
const compare = (direction) => {
if (direction === 'asc') {
return (a, b) => a > b ? 1 : -1;
} else if (direction === 'desc') {
return (a, b) => b > a ? 1 : -1;
}
}
console.log('Asc order: ', data.sort(compare('asc')));
console.log('Desc order: ', clone.sort(compare('desc')));
.as-console-wrapper {min-height: 100% !important; top: 0;}
Upvotes: 1
Reputation: 1292
You can use localeCompare. You code will look like this.
const sortAlphabetically = () => {
setState(state => ({
...state,
items: items.sort((a,b)=>( sort === 'alpha' ? a.localeCompare(b) : -1*a.localeCompare(b))
}));
};
Please let me know if I missed anything.
Upvotes: 1
Reputation: 36
[edit] You must call alphabetize inside of the compare function like so:
const compare = () => {
const alphabetize = () => {
...stuff
}
alphabetize()
}
And a side note: JS Comes with a sort and a reverse function:
var sortAlphabets = (text, direction) =>
direction === "reverseAlpha"
? text
.split("")
.sort()
.reverse("")
.join("")
: text
.split("")
.sort()
.join("");
Upvotes: 1