Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

javascript - 以与另一个数组相同的顺序对数组进行排序(Sort an array in the same order of another array)

I have a few arrays of 50+ names like this.

(我有一些这样的50多个名称数组。)

["dan", "ryan", "bob", "steven", "corbin"]
["bob", "dan", "steven", "corbin"]

I have another array that has the correct order.

(我有另一个具有正确顺序的数组。)

Note that the second array above does not include all of the names, but I still want it to follow the order of the following:

(请注意,上面的第二个数组并不包含所有名称,但是我仍然希望它遵循以下顺序:)

["ryan", "corbin", "dan", "steven", "bob"]

There is no logical order to it, they are just in this order.

(它没有逻辑顺序,它们只是这个顺序。)

What makes sense to me is to compare each array against the correctly ordered one.

(对我来说有意义的是将每个数组与正确排序的数组进行比较。)

I think I saw some people doing this with PHP, but I was not able to find a JavaScript solution.

(我想我看到有人用PHP做到这一点,但我找不到JavaScript解决方案。)

Does anyone have any idea how to do this?

(有谁知道如何做到这一点?)

I've been trying for a few hours and I'm stumped.

(我已经尝试了几个小时,却很沮丧。)

  ask by BarryMode translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use indexOf() to get the position of each element in the reference array, and use that in your comparison function.

(使用indexOf()获取参考数组中每个元素的位置,并在比较函数中使用它。)

 var reference_array = ["ryan", "corbin", "dan", "steven", "bob"]; var array = ["bob", "dan", "steven", "corbin"]; array.sort(function(a, b) { return reference_array.indexOf(a) - reference_array.indexOf(b); }); console.log(array); // ["corbin", "dan", "steven", "bob"] 

Searching the reference array every time will be inefficient for large arrays.

(每次搜索参考数组对于大型数组而言都是低效率的。)

If this is a problem, you can convert it into an object that maps names to positions:

(如果存在问题,可以将其转换为将名称映射到位置的对象:)

 var reference_array = ["ryan", "corbin", "dan", "steven", "bob"]; reference_object = {}; for (var i = 0; i < reference_array.length; i++) { reference_object[reference_array[i]] = i; } var array = ["bob", "dan", "steven", "corbin"]; array.sort(function(a, b) { return reference_object[a] - reference_object[b]; }); console.log(array); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...