[英]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
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.