我能够弄清楚如何从具有多个对象的关联数组中返回最大数。但是我需要整个对象。
我准备了这个例子:
var data = [
{ nr: 235, text: "foo" }
,{ nr: 351, text: "bar" }
];
var highestNr = Math.max.apply(null, Object.keys(data).map(function(e) {
return data[e]['nr'];
}));
var index = "???";
console.log("Highest 'nr': " + highestNr);
console.log("Index at nr "+ highestNr + ": " + index);
//console.log(data[index]);
我需要索引或整个对象。我需要显示对象编号最高的文本。
答案 0 :(得分:7)
您可以通过选择一个值更大的数组来减少数组。
var data = [{ nr: 235, text: "foo" }, { nr: 351, text: "bar" }],
topNr = data.reduce((a, b) => a.nr > b.nr ? a : b);
console.log(topNr);
答案 1 :(得分:3)
您可以按“ nr”属性对数组进行降序排序,并获得第一个元素“ [0]”
var data = [
{ nr: 235, text: "foo" }
,{ nr: 351, text: "bar" }
];
// slice added so that original data is not mutated
var result = data.slice(0).sort((a,b) => b.nr - a.nr)[0]
console.log(result)
答案 2 :(得分:1)
您还可以使用findIndex()方法:
/*Declare necessary variables*/
DECLARE @startIndex INT
DECLARE @endIndex INT
DECLARE @startReplace INT
DECLARE @lengthReplace INT
DECLARE @replaceString VARCHAR(500)
/*Get the index of the start/end idenfier*/
SELECT @startIndex = CHARINDEX ( @startIdenfier , @originalString)
SELECT @endIndex = CHARINDEX ( @startIdenfier , @originalString, @startIndex+1)
/*In case the end idenfier doesn't exist*/
IF @endIndex = 0
SET @endIndex = LEN(@originalString) + 1
SET @startReplace = @startIndex + len(@startIdenfier)
SET @lengthReplace = @endIndex - @startReplace
SELECT STUFF(@originalString, @startReplace, @lengthReplace, @newString)