根据第二个数组问题对第一个数组进行排序 [英] Sort first array based on second array issue

查看:147
本文介绍了根据第二个数组问题对第一个数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据第二个数组中的排序顺序对JavaScript数组进行排序.我已经在SO中经历了其他类似的问题,并提出了以下代码.是输出没有达到预期的结果.

var legends = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];

legends.sort( function (a, b) {
    return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];   
  });


console.log(legends);

所需的输出是

["Chemistry", "Maths", "French", "English", "Physics"];

  • 化学表示排序顺序-3
  • 数学下一个更高的计数,即1
  • 法语下一个更高的数字,即200

我正在尝试使用纯JS或使用D3js获得所需的输出,不确定我是否做对了!

解决方案

您几乎是对的,但是在sort函数中,您引用的是正在变异的legends数组,因此索引与原始顺序不匹配.

要证明是这种情况,可以复制数组并对副本进行排序:

 var legends = ["Maths","Physics","English","French","Chemistry"];
var legendsToSort = ["Maths","Physics","English","French","Chemistry"];

var sortOrder = [1,400,300,200,-3];

legendsToSort.sort( function (a, b) {
    return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];   
  });


console.log(legendsToSort); 

I am trying to sort a JavaScript array based on sort order in a second array. I have already gone through other similar questions here in SO and came up with the below code. Be the output is not getting as expected.

var legends = ["Maths","Physics","English","French","Chemistry"];
var sortOrder = [1,400,300,200,-3];

legends.sort( function (a, b) {
    return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];   
  });


console.log(legends);

The desired output is

["Chemistry", "Maths", "French", "English", "Physics"];

  • Chemistry denotes the sort order -3
  • Maths next higher count, that is 1
  • French next higher count, that is 200

I am trying to get the desired output either in pure JS or using D3js, not sure if I am doing it right!

解决方案

You are almost right but in the sort function, you refer to legends array which is being mutated, so indexes does not match to original order.

To demonstrate that this is the case, you could copy the array and sort the copy:

var legends = ["Maths","Physics","English","French","Chemistry"];
var legendsToSort = ["Maths","Physics","English","French","Chemistry"];

var sortOrder = [1,400,300,200,-3];

legendsToSort.sort( function (a, b) {
    return sortOrder[legends.indexOf(a)] >= sortOrder[legends.indexOf(b)];   
  });


console.log(legendsToSort);

这篇关于根据第二个数组问题对第一个数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆