javascript 如何按波斯字母表排序列表?

vxf3dgd4  于 2023-02-07  发布在  Java
关注(0)|答案(7)|浏览(126)

如何在ul li中读取testArrray并对该列表进行排序?
lis.sort(function(a,b))支持英语/阿拉伯语/和字母表,不支持波斯语字母表。请帮助我。谢谢

var alphabets = ["ا", "ب", "پ", "ت", "ث", "ج", "چ", "ح", "خ", "د", "ذ", "ر", "ز", "ژ", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق",
  "ک", "گ", "ل", "م", "ن", "و", "ه", "ی", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
];
var testArrray = ["ی", "گ", "ژ", "پ"];

var aChar;
var bChar;

function OrderFunc() {
  testArrray.sort(function(a, b) {
    return CharCompare(a, b, 0);
  });
  document.getElementById("result").innerHTML = testArrray;;
}

function CharCompare(a, b, index) {
  if (index == a.length || index == b.length)
    return 0;
    
  aChar = alphabets.indexOf(a.toUpperCase().charAt(index));
  bChar = alphabets.indexOf(b.toUpperCase().charAt(index));
  
  if (aChar != bChar)
    return aChar - bChar
  else
    return CharCompare(a, b, index + 1)
}
<html>
<head></head>
<body onload="OrderFunc()">
  <div id="result"></div>
  <ul class="myul">
    <li>ی</li>
    <li>پ</li>
    <li>گ</li>
    <li>ژ</li>
  </ul>
</body>
</html>
7kjnsjlb

7kjnsjlb1#

String#localeCompare应该能够识别区域设置并适当地比较字符串,因此:

function OrderFunc() {
  // Get the list
  const ul = document.querySelector(".myul");
  // Get its items as an array
  const lis = [...ul.querySelectorAll("li")];
  // Sort the array with localeCompare
  lis.sort((a, b) => a.textContent.localeCompare(b.textContent));
  // Move each of them to the end of the list; this
  // puts them back in order
  for (const li of lis) {
    ul.appendChild(li);
  }
}

示例:
x一个一个一个一个x一个一个二个x
您可能需要将一些选项传递给localeCompare,请参阅ECMAScript®国际化API规范了解更多信息。
你在评论中问:
我会做什么第一波斯语和第二英语单词?
如果你想知道在列表中如何将波斯语单词排在英语单词之前,我想你可能需要检测文本是用什么脚本写的。你应该可以用JavaScript正则表达式来做这件事,但是这个特性(Unicode属性替换)是新的,还没有得到很好的支持。不过你可以用XRegExp library来做这件事:

// This checks to see if the FULL string is in Arabic script; you'll
// probably have to adjust it to fix your use case
const rexArabic = XRegExp("^\\p{Arabic}+$");
function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort(({textContent: a}, {textContent: b}) => {
        const aArabicScript = rexArabic.test(a);
        const bArabicScript = rexArabic.test(b);
        if (aArabicScript && !bArabicScript) {
            // `a` is in Arabic script, `b` isn't; `a` should be first
            return -1;
        }
        if (!aArabicScript && bArabicScript) {
            // `b` is in Arabic script, `a` isn't; `b` should be first
            return 1;
        }
        // They're in the same script
        return a.localeCompare(b);
    });
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}

示例:

// This checks to see if the FULL string is in Arabic script; you'll
// probably have to adjust it to fix your use case
const rexArabic = XRegExp("^\\p{Arabic}+$");
function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort(({textContent: a}, {textContent: b}) => {
        const aArabicScript = rexArabic.test(a);
        const bArabicScript = rexArabic.test(b);
        if (aArabicScript && !bArabicScript) {
            // `a` is in Arabic script, `b` isn't; `a` should be first
            return -1;
        }
        if (!aArabicScript && bArabicScript) {
            // `b` is in Arabic script, `a` isn't; `b` should be first
            return 1;
        }
        // They're in the same script
        return a.localeCompare(b);
    });
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}
OrderFunc();
<div id="result"></div>
<ul class="myul">
<li>ی</li>
<li>پ</li>
<li>Some English</li>
<li>گ</li>
<li>More English</li>
<li>ژ</li>
</ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.2.0/xregexp-all.min.js"></script>
ufj5ltwl

ufj5ltwl2#

为了在Persion中按字母顺序对列表进行排序,我在<meta charset="utf-8">中使用了以下代码,其结果非常完美:

const myList = ["ی","گ","پ", "ژ"];
const collator = new Intl.Collator('fa');  
const sortedLetters = myList.sort(collator.compare);  
console.log(sortedLetters);

Intl.Collator对象启用区分语言的字符串比较。
对于其他语言,可以将fa:

ar — Arabic
bg — Bulgarian
ca — Catalan
zh-Hans — Chinese, Han (Simplified variant)
cs — Czech
da — Danish
de — German
el — Modern Greek (1453 and later)
en — English
es — Spanish
fi — Finnish ,....

有关详细信息,请访问https://dev.to/aumayeung/comparing-non-english-strings-with-javascript-collators-57bfhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator

s1ag04yj

s1ag04yj3#

我从来没有测试过它,也真的做不到,因为我不知道在阿拉伯语中哪个字母在前面或后面,但我可以为您指出正确的方向。您需要以类似于以下的方式使用localeCompare:

arr.sort((x,y)=>x.localeCompare(y, 'ar-ma'))

ar-ma是Arabian摩洛哥语言代码,您应该根据需要更改为语言代码。

gab6jxml

gab6jxml4#

我有同样的问题,我写了这个函数,它很适合我..所以我决定在这里分享给你:

// costome order of english and persian letters 
var persianAlphabets = [" ", "آ", "ا", "ب", "پ", "ت", "ث", "ج", "چ", "ح", "خ", "د", "ذ", "ر", "ز", "ژ", "س", "ش", "ص", "ض", "ط", "ظ", "ع", "غ", "ف", "ق", "ک", "گ", "ل", "م", "ن", "و", "ه", "ی", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

// function for sorting an array of persian words 
function customSort(x, y) {
  var i = 0;
  var maxLen = Math.min(x.length, y.length);

  function increseIndex() {
    if (persianAlphabets.indexOf(x[i]) == persianAlphabets.indexOf(y[i]) &&
      i <= maxLen) {
      i++;
      increseIndex();
    } else return
  }
  increseIndex();

  if (persianAlphabets.indexOf(x[i]) <
    persianAlphabets.indexOf(y[i])) {
    return -1;
  }
  if (persianAlphabets.indexOf(x[i]) >
    persianAlphabets.indexOf(y[i])) {
    return 1;
  }
  return 0;
}

// sample array for testing 
var testArrray = [
  "بابا",
  "آبادان",
  "آب",
  "احمد آقا",
  "احد محمدی",
  "احد مرادی",
  "یونس",
  "مادر 1",
  "آبادانی",
  "ش س",
  "شگیرا",
  "یدالله",
  "مادر 2",
  "سلام"
];

// applying the sorting function 
testArrray.sort(customSort);

// testing resoults 
console.log(testArrray);
pjngdqdw

pjngdqdw5#

Crowder给出了正确的答案。但是如果你想自己动手,你可以应用你的定制排序函数,它通过比较引用数组中的索引来排序。

var alphabets = ["ا", "ب", "پ", "ت", "ث", "ج","چ","ح","خ","د","ذ","ر","ز","ژ","س","ش","ص","ض","ط","ظ","ع","غ","ف","ق","ک","گ","ل","م","ن","و","ه","ی","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

var testArrray = ["ی","گ","ژ","پ"];
testArrray.sort(customSort(alphabets));
function customSort(alphabets){
    return function (x,y) {
      if (alphabets.indexOf(x) < alphabets.indexOf(y)) {
        return -1;
      }
      if (alphabets.indexOf(x) > alphabets.indexOf(y)) {
        return 1;
      }
      return 0;
  }
}
console.log(testArrray);
xu3bshqb

xu3bshqb6#

function OrderFunc() {
    // Get the list
    const ul = document.querySelector(".myul");
    // Get its items as an array
    const lis = [...ul.querySelectorAll("li")];
    // Sort the array with localeCompare
    lis.sort((a, b) => a.textContent.localeCompare(b.textContent));
    // Move each of them to the end of the list; this
    // puts them back in order
    for (const li of lis) {
        ul.appendChild(li);
    }
}
OrderFunc();
<div id="result"></div>
<ul class="myul">
<li>ی</li>
<li>پ</li>
<li>گ</li>
<li>ژ</li>
</ul>
vulvrdjw

vulvrdjw7#

这是我的最佳解决方案:

function PersianSort(words,target) {
    var els = $(words).get();
    els.sort(function(el1, el2){
        return $(el1).text().trim().localeCompare($(el2).text().trim())
    });
    $(target).append(els)
}
ul.container li {
   padding:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="PersianSort('.container li','.container')" type="button" value="1">Sort</button>
<ul class="container">
  <li>هستی</li>
  <li>گلی</li>
  <li>Reza</li>
  <li>چکامه</li>
  <li>Amir</li>
  <li>ویدا</li>
  <li>ژاله</li>
  <li>Ramin</li>
  <li>پوران</li>
  <li>یگانه</li>
  <li>آناهیتا</li>
  <li>آلاله</li>
</ul>

相关问题