gpt4 book ai didi

javascript - 我们如何根据 Node js中的另一个对象数组值对对象数组进行排序

转载 作者:搜寻专家 更新时间:2023-11-01 00:36:35 26 4
gpt4 key购买 nike

我们如何根据另一个对象数组值对对象数组进行排序,就像我们有一个对象数组一样:

var _userEnd = [{"userID":554,"tEnd":6},{"userID":597,"tEnd":3},{"userID":605,"tEnd":3},{"userID":617,"tEnd":1},{"userID":553,"tEnd":1},{"userID":616,"tEnd":1},{"userID":596,"tEnd":0}]

在此索引 1、2、3、4、5 具有与键“tEnd”相同的值,即 3 和 1,所以我只需要根据另一个对象数组对这些索引进行排序

var _profsort=[{"userID":596,"score":100},{"userID":616,"score":95},{"userID":553,"score":100},{"userID":617,"score":85},{"userID":605,"score":95},{"userID":597,"score":85},{"userID":554,"score":100}]

此处用户 ID 597,605,617,553,616 的分值是 85,95,85,100,95

所以根据分数,我想对我的第一个数组进行排序输出应该是:

[{"userID":554,"tEnd":6},{"userID":605,"tEnd":3},{"userID":597,"tEnd":3},{"userID":553,"tEnd":1},{"userID":616,"tEnd":1},{"userID":617,"tEnd":1},{"userID":596,"tEnd":0}]

最佳答案

您可以获取 tEnd 的增量并找到 score 并获取该增量。

function getScore(uID) {
return (_profsort.find(({ userID }) => userID === uID) || { score: 0 }).score;
}

var _userEnd = [{ userID: 554, tEnd: 6 }, { userID: 597, tEnd: 3 }, { userID: 605, tEnd: 3 }, { userID: 617, tEnd: 1 }, { userID: 553, tEnd: 1 }, { userID: 616, tEnd: 1 }, { userID: 596, tEnd: 0 }],
_profsort = [{ userID: 596, score: 100 }, { userID: 616, score: 95 }, { userID: 553, score: 100 }, { userID: 617, score: 85 }, { userID: 605, score: 95 }, { userID: 597, score: 85 }, { userID: 554, score: 100 }];

_userEnd.sort(function (a, b) {
return b.tEnd - a.tEnd || getScore(b.userID) - getScore(a.userID);
});

console.log(_userEnd);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 我们如何根据 Node js中的另一个对象数组值对对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49512542/

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