简体   繁体   中英

Sorting non-Latin strings does not work

I have an issues with sorting on non-Latin strings of array object. I have used this _.sortBy(object, 'name') in my code to sort on name. Here is my array for Persian text:

[['id':1,'name':'ب'],['id':2,'name':'ج'],['id':3,'name':'اما']]

And output should be like this after sorting:

['id':3,'name':'اما'],['id':1,'name':'ب'],['id':2,'name':'ج']

But it's not giving this output. Does anyone have idea about this?

First you need to correct your Array. It has an invalid format.

var a = [{'id':1,'name':'ب'},{'id':2,'name':'ج'},{'id':3,'name':'اما'}];

a.sort(function(a, b) {

  if (a.name > b.name) {

    return true;
  }
});

Input : [{'id':1,'name':'ب'},{'id':2,'name':'ج'},{'id':3,'name':'اما'}]

Output : [{'id':3,'name':'اما'},{'id':1,'name':'ب'},{'id':2,'name':'ج'}]

You can use String#codePointAt to get the Unicode value of a character.

arr.sort((a, b) => a.name.codePointAt(0) - b.name.codePointAt(0))

 var arr = [{ 'id': 1, 'name': 'ب' }, { 'id': 2, 'name': 'ج' }, { 'id': 3, 'name': 'اما' }]; var sortedArr = arr.sort((a, b) => a.name.codePointAt(0) - b.name.codePointAt(0)); document.body.innerHTML = '<pre>' + JSON.stringify(sortedArr, 0, 4); 

Note that the syntax is wrong in the OP code. Use array of objects.

It is best to use the standard string function localeCompare to compare non-english strings:

var arr = [{'id':1,'name':'ب'},{'id':2,'name':'ج'},{'id':3,'name':'اما'}];
arr.sort(function(first, second ) {
    return first.name.localeCompare(second.name);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM