我有这样的数组
[{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
}
);
答案 0 :(得分:1)
您可以使用搜索过滤指定年份的值,然后按降序排序。
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; }
答案 1 :(得分:0)
这是:
var ar = [{
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
}]
}
];
function compare2018Only(a, b) {
valA = a.map.filter(obj => obj.year == 2018)[0];
valB = b.map.filter(obj => obj.year == 2018)[0];
return valB.volume - valA.volume;
}
var result = ar.sort(compare2018Only);
console.log(result);
&#13;