以与另一个数组相同的顺序对数组进行排序

编程入门 行业动态 更新时间:2024-10-24 08:23:42
本文介绍了以与另一个数组相同的顺序对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些包含 50 多个这样的名字的数组.

["dan", "ryan", "bob", "steven", "corbin"][鲍勃"、丹"、史蒂文"、科尔宾"]

我有另一个具有正确顺序的数组.请注意,上面的第二个数组不包括所有名称,但我仍然希望它遵循以下顺序:

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

它没有逻辑顺序,它们只是按照这个顺序.对我来说有意义的是将每个数组与正确排序的数组进行比较.我想我看到有些人用 PHP 做这件事,但我找不到 JavaScript 解决方案.有谁知道如何做到这一点?我已经尝试了几个小时,但被难住了.

解决方案

使用 indexOf() 获取每个元素在引用数组中的位置,并在您的比较函数中使用.>

var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];var array = ["bob", "dan", "steven", "corbin"];数组排序(函数(a,b){返回 reference_array.indexOf(a) - reference_array.indexOf(b);});控制台日志(数组);//["corbin", "dan", "steven", "bob"]

每次搜索参考数组对于大数组来说效率很低.如果这是一个问题,您可以将其转换为将名称映射到位置的对象:

var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];参考对象 = {};for (var i = 0; i

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

["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. Does anyone have any idea how to do this? I've been trying for a few hours and I'm stumped.

解决方案

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

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);

更多推荐

以与另一个数组相同的顺序对数组进行排序

本文发布于:2023-11-30 00:54:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   顺序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!