0

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?

1 Answer 1

1

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

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

2 Comments

still sorting incorrect, ` fff, school test, YMCA CDC @ Woodlands, YMCA CDC @ Zhenghua YMCA CDC, @ Bukit Batok, Sunflower Kinderhub LLP,hkhkhkh`
I found reason, it sort first with uppercase letter, then it sort with lowercase

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.