我有类似的结构:
var array = [
{
"overall": 8,
"date": "2016-03-15",
"review": "bla bla",
},
{
"overall": 6,
"date": "2016-01-19",
"review": "asfasfsadfsd",
},
{
"overall": 7,
"date": "2016-01-23",
"review": "adfsasfdasfas",
}];
返回最高值:
var highestScore = Math.max.apply(Math,array.map(function(o){return o.overall;}));
如何过滤此数组以获取与最新日期的最高总体价值相关的评论?在这种情况下“bla bla”
答案 0 :(得分:3)
无需对数组进行排序,因为您只想获得最高值。因此,请使用 reduce()
并使用 Date.parse()
来比较日期字符串。
var array = [{
"overall": 5,
"date": "2016-03-15",
"review": "sadas sasdadasdas",
}, {
"overall": 6,
"date": "2016-01-19",
"review": "asfasfsadfsd",
}, {
"overall": 9,
"date": "2016-03-15",
"review": "sadas sasdadasdas",
}, {
"overall": 7,
"date": "2016-01-23",
"review": "adfsasfdasfas",
}];
var res = array.reduce(function(a, b) {
// parse the date
var d1 = Date.parse(a.date),
d2 = Date.parse(b.date);
// if dates are equal compare value of overall and return value , else return based on date
return d1 == d2 ? (a.overall > b.overall ? a : b) : (d1 > d2 ? a : b);
}).overall; // get overall value from final object
document.write(res);
答案 1 :(得分:2)
您可以使用.sort()
。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
var array = [{
"overall": 5,
"date": "2016-03-15",
"review": "sadas sasdadasdas",
}, {
"overall": 6,
"date": "2016-01-19",
"review": "asfasfsadfsd",
}, {
"overall": 7,
"date": "2016-01-23",
"review": "adfsasfdasfas",
}];
var sortedArray = array.sort(function(a, b) {
var aDate = Date.parse(a.date);
var bDate = Date.parse(b.date);
if (aDate > bDate) {
return true;
} else if(aDate == bDate) {
return a.overall > b.overall;
} else {
return false;
}
});
//hello
var isItMeYoureLookingFor = sortedArray[0];
基本上,按标准排序,取第一个:)。
答案 2 :(得分:1)
使用普通数组迭代:
function newestHighestOverall(arr){
if(arr.length == 0) return 0;
var latestDate = new Date(arr[0].date);
var highestOverall = arr[0].overall;
for(var i=0;i<arr.length;i++){
if(latestDate < new Date(arr[i].date)){
highestOverall = arr[i].overall;
latestDate = new Date(arr[i].date);
}else if(latestDate == new Date(arr[i].date)){
highestOverall = Math.max(highestOverall, arr[i].overall);
}
}
return highestOverall
}
console.log(newestHighestOverall(array))
答案 3 :(得分:0)
您可以使用sort
并先按date
进行比较,然后按overall
进行比较,并返回评论。
var array = [{
"overall": 8,
"date": "2016-03-15",
"review": "bla bla",
},{
"overall": 20,
"date": "2016-03-15",
"review": "Random bla bla",
}, {
"overall": 6,
"date": "2016-01-19",
"review": "asfasfsadfsd",
}, {
"overall": 7,
"date": "2016-01-23",
"review": "adfsasfdasfas",
}];
result = array.sort((a, b) => {
return Date.parse(b.date) - Date.parse(a.date) || b.overall - a.overall;
})[0].review;
console.log(result)