简体   繁体   English

如何在Jquery中以给定的任何特定排序顺序对字符串数组进行排序

[英]How to sort an array of Strings in Jquery with any specific sort order given

I have and array of strings: 我有和字符串数组:

var arrStr = ["Ron", "Jhon", "Mary", "Alex", "Ben"];

The above array is the default sort order that I require. 上面的数组是我需要的默认排序顺序。 I have another array of Strings: 我还有另一个字符串数组:

var arrStr2 = ["Mary", "Alex", "Jhon"];

I wanted to sort arrStr2 with the sort order in arrStr . 我想排序arrStr2与排序顺序arrStr (the order in arrStr also can be changed, accordingly the arrStr2 should be sorted). (也可以更改arrStr的顺序,因此arrStr2进行排序)。 arrStr2 can have more values also, but the values will be only from any of the values in array arrStr arrStr2也可以有更多值,但是这些值只能来自数组arrStr任何值

After sorting I need an out put for arrStr2 as ["Jhon","Mary","Alex"]; 排序后,我需要arrStr2["Jhon","Mary","Alex"];

How can I achieve this using jQuery? 如何使用jQuery实现此目的?

After sorting I need an out put for arrStr2 as ["Jhon","Mary","Alex"]; 排序后,我需要arrStr2的输出为[“ Jhon”,“ Mary”,“ Alex”];

simply try this 只需尝试这个

arrStr2.sort(function(a,b){ return arrStr.indexOf(a) - arrStr.indexOf(b) });

Now arrStr2 will have the value you are expecting, 现在arrStr2将具有您期望的值,

DEMO 演示

 var arrStr = ["Ron", "Jhon", "Mary", "Alex", "Ben"]; var arrStr2 = ["Mary", "Alex", "Jhon"]; arrStr2.sort(function(a,b){ return arrStr.indexOf(a) - arrStr.indexOf(b) }); document.body.innerHTML = JSON.stringify( arrStr2, 0, 4 ); 

Just compute the intersection, no need to sort() : 只需计算交集,无需sort()

 var arrStr = ["Ron", "Jhon", "Mary", "Alex", "Ben"]; var arrStr2 = ["Mary", "Alex", "Jhon"]; result = arrStr.filter(x => arrStr2.includes(x)) document.write('<pre>'+JSON.stringify(result,0,3)); 

(ES5 backporting left as an exercise). (ES5向后移植为练习)。

This is one more approach: 这是另一种方法:

var rank = {};
arrStr.forEach(function(e, i){rank[e] = i;});
arrStr2.sort(function(a, b) {return rank[a] - rank[b];});

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

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