简体   繁体   English

排序非拉丁字符串不起作用

[英]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. 我在我的代码中使用了这个_.sortBy(object, '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':'اما'}] 输入[{'id':1,'name':'ب'},{'id':2,'name':'ج'},{'id':3,'name':'اما'}]

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

You can use String#codePointAt to get the Unicode value of a character. 您可以使用String#codePointAt来获取字符的Unicode值。

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. 请注意,OP代码中的语法错误。 Use array of objects. 使用对象数组。

It is best to use the standard string function localeCompare to compare non-english strings: 最好使用标准字符串函数localeCompare来比较非英语字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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