我有一个名为checkdata的数组:
<div class="grand-parent">
<div class="parent">
<div class="child green"></div>
<div class="child blue"></div>
</div>
</div>
现在我想要的是在上面的示例数组中获取id的最大值为11并将其存储在变量中。 我已经在php中使用相同的东西工作 max(array_column($ checkdata ['details]],'id')); 。任何人都可以帮助使其在angular js中工作
答案 0 :(得分:0)
您可以实现将最高ID放在首位
的排序方法var arr = [{"name":"aasha","id":"1","age":"25","address":"happay appartment"},{"name":"megha","id":"2","age":"21","address":"viajy nagar"}, {"name":"sujeet","id":"11","age":"38","address":"pb road"}];
var highestId = arr.sort(function(a, b){
return parseInt(b.id) - parseInt(a.id);
})
console.log(highestId[0])
您还可以使用map方法,该方法与上述排序类似,但只会返回不排序的整数数组
var items = arr.map(function(o) { return parseInt(o.id); })
但是您可以在数组上执行Math.max方法以检索最大值:
var max = Math.max.apply(Math, items);
var arr = [{"name":"aasha","id":"1","age":"25","address":"happay appartment"},{"name":"megha","id":"2","age":"21","address":"viajy nagar"}, {"name":"sujeet","id":"11","age":"38","address":"pb road"}];
var highestId = arr.sort(function(a, b){
return parseInt(b.id) - parseInt(a.id);
})
console.log(highestId[0].id)
var items = arr.map(function(o) { return parseInt(o.id); })
var max = Math.max.apply(Math, items);
console.log(max)
答案 1 :(得分:0)
假设name
属性后的缺失引号是一个错字。您可以尝试关注
您可以使用简单的Javascript获得最大值。使用Number
将id
的字符串值转换为数字,并使用Array.reduce
转换为最大值。
var arr = [{"name":"aasha","id":"1","age":"25","address":"happay appartment"},
{"name":"megha","id":"2","age":"21","address":"viajy nagar"},
{"name":"sujeet","id":"11","age":"38","address":"pb road"}];
var id = arr.reduce((a,{id}) => Number(id) > a ? Number(id) : a , -1);
console.log(id);