gpt4 book ai didi

javascript - 如何根据嵌套属性值n javascript对数据进行排序

转载 作者:行者123 更新时间:2023-12-03 03:20:41 25 4
gpt4 key购买 nike

我有这样的数组

   [{key:'A',map:[{
volume:2000,
year:2017
},{
volume:2000,
year:2018
}]
},
{key:'B',map:[{
volume:2000,
year:2017
},{
volume:1000,
year:2018
}]
},
{key:'C',map:[{
volume:2000,
year:2017
},{
volume:3000,
year:2018
}]
}
]

现在我必须根据数量或特定年份对其进行排序,即如果我对 2018 年的数量进行排序,我的结果应该是这样的

[{key:'C',map:[{
volume:2000,
year:2017
},{
volume:3000,
year:2018
}]
},
{key:'A',map:[{
volume:2000,
year:2017
},{
volume:2000,
year:2018
}]
},
{key:'B',map:[{
volume:2000,
year:2017
},{
volume:1000,
year:2018
}]
}
]

我尝试使用java脚本正常排序,但它没有帮助,请有人让我知道如何做到这一点?

编辑1:这是我的排序函数

 sortedData = currentYearData.sort(
function(a,b){
let aData = a.map(data => data.map).filter(data => data.year === 2018);
let bData = b.map(data => data.map).filter(data => data.year === 2018);
if(aData.volume < bData.volume)
return 1;
if(bData.volume < aData.volume)
return -1;
else
return 0
}
);

最佳答案

您可以使用搜索过滤指定年份的值,然后降序排序。

var data = [{ key: 'A', map: [{ volume: 2000, year: 2017 }, { volume: 2000, year: 2018 }] }, { key: 'B', map: [{ volume: 2000, year: 2017 }, { volume: 1000, year: 2018 }] }, { key: 'C', map: [{ volume: 2000, year: 2017 }, { volume: 3000, year: 2018 }] }];

data.sort(function (a, b) {
function getValue(array) {
var value;
array.some(function (a) {
if (a.year === 2018) {
value = a.volume;
return true;
}
});
return value;
}
return getValue(b.map) - getValue(a.map);
});

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

ES6

var data = [{ key: 'A', map: [{ volume: 2000, year: 2017 }, { volume: 2000, year: 2018 }] }, { key: 'B', map: [{ volume: 2000, year: 2017 }, { volume: 1000, year: 2018 }] }, { key: 'C', map: [{ volume: 2000, year: 2017 }, { volume: 3000, year: 2018 }] }],
fn = o => o.year === 2018;

data.sort((a, b) => b.map.find(fn).volume - a.map.find(fn).volume);

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

关于javascript - 如何根据嵌套属性值n javascript对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46585917/

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