对javascript或jquery中的单词进行比较后的列表值进行排序

sort list value after comparing a word in javascript or jquery

本文关键字:列表 排序 比较 单词进 javascript jquery      更新时间:2023-09-26

我想在与一个单词进行比较后对列表标记进行排序,比如如果多个语句中有单词"one",那么它应该首先排序,然后在其他语句中检查其他单词,比如其余语句中的"two",那么这个有单词"two)的语句应该在包含"one"的语句之后。请大家帮我写逻辑。看看我的代码,我只用于按字母顺序排序(基于下面代码中给出的状态)示例:类似于

  • manoj kumar
  • rohit koul
  • sachin kumar
,所以在这三个列表中,我想首先对包含"kumar"字符串的人进行排序,然后等等。。
<script id="template" type="text/html">
<ul class="checklist" data-role="listview" data-inset="true" data-autodividers="true"     id="mylist">
{{#container}}
{{#nid}}<li><a href="checklist-detail.html?nid={{nid}}">{{name}} - {{status}} {{#date}}<br/>
   <span class="due-date">{{date}}</span>{{/date}}</a></li>{{/nid}}
      {{/container}}
 </ul>
</script>
look once my javascript code but this is not for my desire code it is only
 for sort  alphabetically (help me in this code that how to i write 
  condition or logic for sort according to particular word comparison)
      var mylist = $('ul');
       var listitems = mylist.children('li').get();
      listitems.sort(function(a, b) {
      var compA = $(a).text().toUpperCase();
     var compB = $(b).text().toUpperCase();
     return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    });
 $.each(listitems, function(idx, itm) { mylist.append(itm); });

您可以根据标签是否包含预定义的有序单词列表中的单词来给标签打分。例如:

var ordered_words = ["kumar", "koul", "simon"]
var tags = ["manoj kumar", "rohit koul", "sachin kumar", "simon f (me)"]
var scored_tags = []
var i = 0, tag
while (tag = tags[i]) {
    var j = 0, word, found = false
    while (found == false && j < ordered_words.length) {
        word = ordered_words[j]
        if (tag.indexOf(word) != -1) {
            scored_tags.push({tag: tag, score: j})
            found = true
        }
        j++
    }
    i++
}
console.log(scored_tags)

这将输出:

[ { tag: 'manoj kumar', score: 0 },
  { tag: 'rohit koul', score: 1 },
  { tag: 'sachin kumar', score: 0 },
  { tag: 'simon f (me)', score: 2 } ]

然后,您可以使用得分参数对该数组进行排序,如下所示:

scored_tags.sort(function(a, b) {
      var compA = a.score
      var compB = b.score
      return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});

这是你可以玩的代码:

http://repl.it/Yil/2