我有一個“參考”陣列,其中包含
[“Push”,”Pull, “Leg”]
和一系列看起來像
{
"bodyPart": "upper arms",
"target": "biceps",
"broad_target": "biceps",
"ppl": "pull"
},
{
"bodyPart": "chest",
"target": "pectorals",
"broad_target": "chest",
"ppl": "push"
},
{
"bodyPart": "lower legs",
"target": "calves",
"broad_target": "legs",
"ppl": "legs"
},
我希望基于參考陣列的 PPL 屬性對陣列進行排序。
因此,由于參考陣列是push, pull, leg,字典陣列應該看起來像
{
"bodyPart": "chest",
"target": "pectorals",
"broad_target": "chest",
"ppl": "push"
},
{
"bodyPart": "upper arms",
"target": "biceps",
"broad_target": "biceps",
"ppl": "pull"
},
{
"bodyPart": "lower legs",
"target": "calves",
"broad_target": "legs",
"ppl": "legs"
},
uj5u.com熱心網友回復:
根據參考陣列上屬性的索引使用 Javascriptsort函式(您可以使用 function 獲取此索引)。這是一個可愛的單線:pplindexOf
// Reference array
const arrRef = ["Push", "Pull", "Leg"];
// Dictionary array (order "Push - Leg - Push")
const arrDicts = [
{ "ppl": "Push" },
{ "ppl": "Leg" },
{ "ppl": "Push" },
];
// Sorting (should be "Push - Push - Leg")
arrDicts.sort((a, b) => arrRef.indexOf(a.ppl) - arrRef.indexOf(b.ppl));
編輯:添加舊的建議解決方案(備份陣列)
const arrRef = ["Push", "Pull", "Leg"];
const arrDicts = [
{
"bodyPart": "upper arms",
"target": "biceps",
"broad_target": "biceps",
"ppl": "Push"
},
{
"bodyPart": "chest",
"target": "pectorals",
"broad_target": "chest",
"ppl": "Pull"
},
{
"bodyPart": "lower legs",
"target": "calves",
"broad_target": "legs",
"ppl": "Leg"
},
];
// Create a back up array and iterate on the reference array, filtering the actual dicitionary array with `ppl == current reference`
const backupArr = [];
for (const ref of arrRef)
backupArr.push(...arrDicts.filter(x => x.ppl == ref))
// Now backupArr is ordered as you want to
console.log(backupArr)
請考慮這種對陣列進行排序的方式將不包括字典陣列中具有ppl不在參考陣列中的屬性的物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/434353.html
上一篇:沒有已知的引數1從'int'到'gnu_cxx::normal_iterator<int*,std::vector<int>>&&'的轉
