我有以下对象:
var questions = [{
'question_id': 245,
'question': 'Question 1',
'ordinal': 1,
'master_difficulty': 1,
'overridden_difficulty': ''
},{
'question_id': 34,
'question': 'Question 2',
'ordinal': 2,
'master_difficulty': 1,
'overridden_difficulty': ''
},{
'question_id': 656,
'question': 'Question 3',
'ordinal': 3,
'master_difficulty': 1,
'overridden_difficulty': ''
},{
'question_id': 86,
'question': 'Question 4',
'ordinal': 4,
'master_difficulty': 1,
'overridden_difficulty': ''
}]
我想从中获得最高的序数值。
例如var highestOrdinal = highestOrdinalFunction(questions);
哪里highestOrdinalFunction
将返回最大序数。
所以在这种情况下它将返回 4
.
可以Math.max
为此工作?
最佳答案
Array#reduce
( spec | MDN ) 是执行以下操作的惯用方法:
function highestOrdinalFunction() {
return questions.reduce(function(previous, entry) {
return previous === undefined || entry.ordinal > previous ? entry.ordinal : previous;
}, undefined);
}
Array#reduce
重复调用回调,传入回调之前的返回值,该值以 reduce
的第二个参数作为种子。这个东西通常被称为归约操作的“累加器”。 reduce
的结果是累加器的最终值。
如果questions
为空,上面将返回undefined
。
关于javascript - 从 JavaScript 对象中的键查找最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938824/