简体   繁体   English

如何使用Javascript基于另一个数组的相应元素的属性对数组进行排序?

[英]How do I sort an array based on the attribute of corresponding elements of another array using Javascript?

Say I have two arrays. 说我有两个数组。 One is : 一个是:

A = [a, b, c, d]

and another is, 另一个是,

B = [w, x, y, z]

Each element in A corresponds to the respective element in B A中的每个元素对应于B中的相应元素

(i.e. a -> w, b -> x, c -> y, d -> z)

Now I want to sort the array A in increasing order of an attribute (say value) of the elements of B 现在我想按照B元素的属性(比如值)的递增顺序对数组A进行排序

(eg. w.value = 3, x.value = 2, y.value = 1, z.value = 4)

Hence, my desired output is: 因此,我想要的输出是:

[c, b, a, d] [c,b,a,d]

How do I do this using Javascript? 我如何使用Javascript执行此操作? Any help will be appreciated. 任何帮助将不胜感激。 I am stuck at this for a long time. 我被困在这里很长一段时间了。

You could get the indices, sort them with values of b and map the values of a by taking sorted indices. 你可以得到的指数,他们的排序值b和值映射a通过采取分类指数。

 var a = ['a', 'b', 'c', 'd'] , b = [3, 2, 1, 4], indices = [...b.keys()].sort((x, y) => b[x] - b[y]), result = indices.map(i => a[i]); console.log(result); 

To achieve expected result, use below option of using indexOf and sort 要获得预期的结果,请使用以下选项使用indexOf和sort

  1. Sort array - a using sort with b array value using the indexOf 排序阵列- 一个使用排序用b数组值使用的indexOf

 var a = ["a", "b", "c", "d"] var b = [3, 2, 1, 4] console.log(a.sort((x,y) => b[a.indexOf(x)] - b[a.indexOf(y)])) 

暂无
暂无

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

相关问题 如何按另一个数组中的相应值对一个数组进行排序? - How do I sort one array by the corresponding values in another array? 如何基于另一个对象数组对一个对象数组进行排序 - How do I sort an array of objects based on another array of objects 如何根据另一个数组的顺序对对象数组进行排序? - How do I sort an array of objects based on the ordering of another array? 如何基于JavaScript中的另一个数组比较和更新此数组? - How do I compare and update this array based on another array in JavaScript? 如何根据另一个数组在Javascript中重新排序此数组? - How do I reorder this array in Javascript based on another array? 在javascript中,如何将数组的元素替换为另一个对象中的对应值? - In javascript how to replace elements of an array to it's corresponding values in another object? 如何基于另一个JavaScript数组对JavaScript中的数组进行排序? - How to Sort an array in JavaScript based on another JavaScript array? 使用javascript基于另一个数组对一个数组进行排序 - Sort one array based on another array using javascript Javascript使用下划线基于另一个数组顺序对数组顺序进行排序 - Javascript Sort array order based on another array order using underscore Javascript,我如何从数组中获取两个相应的元素以使用随机功能同时生成? - Javascript, how do i get two corresponding elements from an array to generate at the same time with the random feature?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM