以与另一数组JavaScript相同的方式对一个数组进行排序 [英] Sort one array the same way as another array JavaScript

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

问题描述

我有2个数组:

[2, 4, -2, 4, 1, 3]
["a", "b", "c", "d", "e", "f"]

并且我希望它们按数值数组排序:

and I want them to be sorted by the numerical array:

// output
[-2, 1, 2, 3, 4, 4] // <-sorted by numerical order
["c", "e", "a", "f", "b", "d"] // sorted exactly the same order as the first array

虽然"b"或"d"排在第一位实际上并不重要(在此示例中,它们都为4)

while its actually not important if "b" or "d" comes first (they both have 4 in this example)

我在网上发现了许多与此有关的问题,但是没有一个对我有用,谁能帮助我解决这个问题?

I found many questions about this online but none of them worked for me can anyone help me with that?

推荐答案

您可以对

You could sort the keys of the first array based on their value. This will return an array with indices of the array sorted based on the value of numbers array. Then use map to get the sorted values based on the indices

const numbers = [2, 4, -2, 4, 1, 3],
      alphabets = ["a", "b", "c", "d", "e", "f"]

const keys = Array.from(numbers.keys()).sort((a, b) => numbers[a] - numbers[b])

const sortedNumbers = keys.map(i => numbers[i]),
      sortedAlphabets = keys.map(i => alphabets[i])

console.log(
  sortedNumbers,
  sortedAlphabets
)

这篇关于以与另一数组JavaScript相同的方式对一个数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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