Reputation: 818
I use algorythm to sort list of names
handleSort(sortColumn, direction){
const comparer = (a, b) => {
if(direction === 'ASC'){
return (a[sortColumn] > b[sortColumn]) ? 1 : -1
} else if (direction === 'DESC') {
return (a[sortColumn] < b[sortColumn]) ? 1 : -1
}
}
const rows = direction == '' ? this.state.rows.slice(0) : this.state.rows.sort(comparer);
this.setState({rows})
}
From A to Z sort like
Sunflower Kinderhub LLP
YMCA CDC @ Bukit Batok
YMCA CDC @ Woodlands
YMCA CDC @ Zhenghua
fff
hkhkhkh
school test
From Z to A sort like:
school test
hkhkhkh
fff
YMCA CDC @ Zhenghua
YMCA CDC @ Woodlands
YMCA CDC @ Bukit Batok
Sunflower Kinderhub LLP
Why it not sorting ?? like :
fff
hkhkhkh
school test
Sunflower Kinderhub LLP
YMCA CDC @ Bukit Batok
YMCA CDC @ Woodlands
YMCA CDC @ Zhenghua
For simple names, that consist from 1 word, working fine.. how to sort name that created from 3 words?
Upvotes: 0
Views: 76
Reputation: 2776
How about using:
a[sortColumn].localeCompare(b[sortColumn])
instead a[sortColumn] > b[sortColumn]
Let's see my example:
var arr = ['Sunflower Kinderhub LLP',
'YMCA CDC @ Bukit Batok',
'YMCA CDC @ Woodlands',
'YMCA CDC @ Zhenghua',
'fff',
'hkhkhkh',
'school test'];
console.log(arr.sort((a,b) => a.localeCompare(b)));
You can see in MDN for more detail https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
Upvotes: 1