我有一个像下面这样的数组
[
{
"key":"Human Resources",
"data":[
{
"id":"1HwahYXr5hs3IDTn7RtC",
"element":{
"id":"1HwahYXr5hs3IDTn7RtC",
"ca":"1x"
},
"groupBy":"Human Resources_Human Resources"
},
{
"id":"I7kCoWl7JLCWvgSdZm6p",
"element":{
"id":"I7kCoWl7JLCWvgSdZm6p",
"ca":"2x"
},
"groupBy":"Human Resources"
}
]
},
{
"key":"Marketing",
"data":[
{
"id":"Ltgk4vvKNILwYry1thXL",
"element":{
"id":"Ltgk4vvKNILwYry1thXL",
"ca":"5x"
},
"groupBy":"Marketing_Marketing"
},
{
"id":"aA43supw5IYmVLkniC8c",
"element":{
"id":"aA43supw5IYmVLkniC8c",
"ca":"6x"
},
"groupBy":"Marketing"
}
]
},
{
"key":"Sales",
"data":[
{
"id":"WwYl7FelUSVo8i5eMYMk",
"element":{
"id":"WwYl7FelUSVo8i5eMYMk",
"ca":"8x"
},
"groupBy":"Sales"
}
]
}
]
我还有另一个数组,存储上面数组中键的排名,如下所示:
[
{
"id":1,
"name":"Marketing",
"rank":2
},
{
"id":1,
"name":"Human Resources",
"rank":1
}
]
我需要根据第二个数组中的键排位对第一个数组进行排序,如果没有第二个键,它将排在最前面。
请注意,有任何inbuit函数可以像lodash中的任何函数一样执行此操作。
谢谢
答案 0 :(得分:0)
您可以将排名或-Infinity
排在未排序的排名前。
var array = [{ key: "Human Resources" }, { key: "Marketing" }, { key: "Sales" }],
ranking = [{ id: 1, name: "Marketing", rank: 2 }, { id: 1, name: "Human Resources", rank: 1 }],
order = ranking.reduce((o, { name, rank }) => (o[name] = rank, o), Object.create(null));
array.sort(({ key: a }, { key: b }) => (order[a] || -Infinity) - (order[b] || -Infinity));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您可以针对每个排序,过滤数据并添加属性范围,然后对数据进行排序
ranking.forEach(x=>{
data.filter(d=>d.key==d.name).forEach(df=>{
df.rank=x.rank; //Add a new property
}
})
ranking.sort((a,b)=>(a.rank || 0)-(b.rank || 0));
我的排名是数组宽度的排名,数据是数组宽度的数据
答案 2 :(得分:0)
这应该有效,
arr.sort((a,b) => {
rank1 = rank.find(e => e.name ===a.key);
rank2 = rank.find(e => e.name ===b.key);
if (!rank1 || !rank2) {
return 1;
}
if (rank1.rank < rank2.rank) {
return -1;
} else {
return 1;
}
})