gpt4 book ai didi

javascript - 根据另一个数组的排序索引对数组进行排序

转载 作者:行者123 更新时间:2023-11-30 10:36:00 24 4
gpt4 key购买 nike

我有两个数组。我应该对一个(降序或升序)进行正常排序,然后根据第一个数组的排序方式对另一个进行排序。这是因为第一个数组中的每个元素都与第二个数组中的相同索引元素有关系,我必须保持这种关系为真。例如:

sortThis=[3,1,2];
sortAccording=["With 3","With 1","With 2];

我找不到任何方法从 JavaScript 的 sort 函数中获取索引更改。

最佳答案

解决方案:为此,您必须将两个数组压缩在一个数组中。这是,假设你有这两个数组:

sortThis=[3,1,2];
sortAccording=["With 3","With 1","With 2];

zip 之后,您将拥有以下数组:

zipped = [{a: 3, b: "With 3"}, {a: 1, b: "With 1"}, {a: 2, b: "With 2"}];

然后,您按 a 对其进行排序,以便:

zippedAndSorted = [{a: 1, b: "With 1"}, {a: 2, b: "With 2"}, {a: 3, b: "With 3"}];

下一步是什么?

好吧,一旦你按照你想要的方式对这个数组进行了排序,你就必须使用 ma​​p 函数提取它们的值,最后你将按照相同的标准对你的两个数组进行排序:

代码:

// your arrays
sortThis=[3,1,2];
sortAccording=["With 3","With 1","With 2"];

// the zip function
function zip(a,b) {
return a.map(function(aa, i){ return { i: aa, j: b[i]};} )
};

// ziping and sorting the arrays
var zipped = zip(sortThis, sortAccording);
zippedAndSorted = zipped.sort(function(a,b){ return a.i - b.i; });

// your two sorted arrays
sortedThis = zippedAndSorted.map(function(a){ return a.i;});
sortedAccording = zippedAndSorted.map(function(a){ return a.j;});

你也可以在这里看到它的工作:http://jsfiddle.net/lontivero/cfpcJ/

祝你好运!

关于javascript - 根据另一个数组的排序索引对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14004188/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com