gpt4 book ai didi

javascript - 对包含数组的字典进行排序作为值和等级

转载 作者:行者123 更新时间:2023-11-30 11:41:35 26 4
gpt4 key购买 nike

我正在寻找尽可能最好、最少的操作来解决这个问题。

var sourceDictionary = {
"200" : [
[ "a", 5 ],
[ "al", 6 ],
[ "xl", 8 ]
],
"201" : [
[ "b", 2 ],
[ "al", 16 ],
[ "al", 26 ],
[ "al", 9 ],
[ "al", 3 ]
],
"202" : [
[ "lm", 7 ]
]
}

我想根据每个键中包含的整数值对字典进行排序,然后对每个值进行排序,如 outputputDictionary 所示。

var targetDictionary = {
"200" : [
[ "a", 5, "rank-7" ],
[ "al", 6, "rank-6" ],
[ "xl", 8, "rank-4" ]
],
"201" : [
[ "b", 2, "rank-9" ],
[ "al", 16, , "rank-2" ],
[ "al", 26, "rank-1" ],
[ "al", 9, "rank-3" ],
[ "al", 3, "rank-8" ]
],
"202" : [
[ "lm", 7, "rank-5" ]
]
}

例如 [ "al", 26, "rank-1"] 。这是 rank-1,因为 26 是所有其他值中的最大值。

Javascript是最优选的语言。寻找最好的最优解

最佳答案

由于数组是通过引用传递的,因此您可以像这样使用它:

function rankify(obj) {
// PHASE 1: get a reference of all the sub-arrays
var references = [];
for(var key in obj) { // for each key in the object obj
obj[key].forEach(function(e) { // for each element e (sub-array) of the array obj[key]
references.push(e); // push a reference of that array into reference array
});
}

// PHASE 2: sort the references
references.sort(function(a, b) { // sort the items
return b[1] - a[1]; // to reverse the sort order (a[1] - b[1])
});

// PHASE 3: assign the ranks
references.forEach(function(e, i) { // for each array in the reference array
e.push("rank-" + (i + 1)); // push another item ("rank-position") where the position is defined by the sort above
});
}


var sourceDictionary = {"200" : [[ "a", 5 ],[ "al", 6 ],[ "xl", 8 ]],"201" : [[ "b", 2 ],[ "al", 16 ],[ "al", 26 ],[ "al", 9 ],[ "al", 3 ]],"202" : [[ "lm", 7 ]]};

rankify(sourceDictionary);
console.log(sourceDictionary);

如果允许使用箭头函数:

function rankify(obj) {
Object.keys(obj)
.reduce((ref, k) => ref.concat(obj[k]), []) // get the references array
.sort((a, b) => b[1] - a[1]) // sort it
.forEach((e, i) => e.push("rank-" + (i + 1))); // assign the rank
}


var sourceDictionary = {"200" : [[ "a", 5 ],[ "al", 6 ],[ "xl", 8 ]],"201" : [[ "b", 2 ],[ "al", 16 ],[ "al", 26 ],[ "al", 9 ],[ "al", 3 ]],"202" : [[ "lm", 7 ]]};

rankify(sourceDictionary);
console.log(sourceDictionary);

关于javascript - 对包含数组的字典进行排序作为值和等级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42443174/

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