简体   繁体   English

根据另一个数组的Javascript自定义排序算法

[英]Javascript custom sort algorithm according to another array

I have this two arrays 我有这两个数组

var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
var beenThere = ['Russia','Bhutan','India']

I need to sort beenThere on the order of refArray for display purpose, so if I sort beenThere , result should be, 为了显示目的,我需要按beenThere的顺序对beedThere进行排序,所以如果我对beenThere进行排序,结果应该是,

['India','Bhutan','Russia']

Where can I get one algorithm. 在哪里可以获得一种算法。

a faster way is to use the pre-sorted array as a template, and limit the indexOf() work to a single indexOf() call on the sub-set items, instead of 2-indexOf() calls on all items. 一种更快的方法是使用预先排序的数组作为模板,并将indexOf()工作限制为对子集项进行单个indexOf()调用,而不是对所有项进行2-indexOf()调用。

var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
var beenThere = ['Russia','Bhutan','India'];
function contains(a){return this.indexOf(a)!==-1; }
refArray.filter(contains, beenThere); // == ["India", "Bhutan", "Russia"]

Try to use indexOf : 尝试使用indexOf

beenThere.sort(function(a, b) {
    return refArray.indexOf(a) - refArray.indexOf(b); 
}); // ['India','Bhutan','Russia']

Just compare the indices of each element in the refArray using indexOf method. 只需使用indexOf方法比较refArray中每个元素的索引。

beenThere.sort(function(a,b){
return refArray.indexOf(a)-refArray.indexOf(b);
})

since the data are strings, and the strings don't have commas, you can avoid all user-land iteration with a dynamic RegExp: 由于数据是字符串,并且字符串没有逗号,因此可以使用动态RegExp避免所有用户域迭代:

var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
var beenThere = ['Russia','Bhutan','India'];


(","+refArray+",").match(RegExp(",("+beenThere.join("|")+"),","g")).join(",").split(/,+/).slice(1,-1); 
// ==  ["India", "Bhutan", "Russia"]

that one is nice in that it doesn't need [].indexOf(), so it works in older browsers. 这样做很不错,因为它不需要[] .indexOf(),因此可以在较旧的浏览器中使用。 you can use another delimeter besides comma if the data has commas, with some slightly uglier code... 如果数据有逗号,则可以使用除逗号以外的其他分隔符,并带有一些较丑陋的代码...

or, using filter for the iteration, but with a native method instead of a user-land function: 或者,使用过滤器进行迭代,但使用本机方法而不是用户界面函数:

var refArray = ['India','Pakistan','Nepal','Bhutan','SreeLanka','Singapore','Thailand','China','Russia']
var beenThere = ['Russia','Bhutan','India'];

refArray.filter(/./.test, RegExp("("+beenThere.join("|")+")","g"));
// == ["India", "Bhutan", "Russia"]

these would probably perform faster than indexOf(), but sorting is a weird operation, with lots of opportunity for behind-the-scenes optimization, so results may vary. 它们的执行速度可能比indexOf()快,但排序是一个奇怪的操作,幕后优化的机会很大,因此结果可能会有所不同。

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

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