2014-06-20 181 views
0

我有一个这样的数组:获取从嵌套数组最小值

[ 
    {'date' : 'date', notifications:[{notificationID:4, name: 'abc' }, {notificationID:1, name: 'abc' }]}, 
    {'date' : 'date', notifications:[{notificationID:3, name: 'abc' }, {notificationID:4, name: 'abc' }]} 
] 

在这种情况下notificationID的最小值为1。所以,强调应返回1.

这里是我的不完整的代码显然不工作,因为它是单个阵列

notificationID = _.min(_.pluck($scope.notificationDetails, "notificationID")); 

任何帮助表示赞赏。

回答

1

你需要一个双勇气:第一个获得所有notifications和第二个从第一获取所有notificationID S:

var arr = [ 
    {'date' : 'date', notifications:[{notificationID:4, name: 'abc' }, {notificationID:1, name: 'abc' }]}, 
    {'date' : 'date', notifications:[{notificationID:3, name: 'abc' }, {notificationID:4, name: 'abc' }]} 
]; 

var notificationID = _.min(_.pluck(_.flatten(_.pluck(arr, 'notifications')), 'notificationID')); 
console.log(notificationID); 
+0

我得到两个无穷的console.log(_采摘(_采摘(。 $ scope.notificationDetails,'notifications'),'notificationID'));.虽然它看起来很有希望,但由于某种原因它不起作用 – Jack

+0

有一个小错误。我加入拼合来加入第一个结果。 – Ingmars

+0

酷!感谢Ingmars – Jack

0

我真的不知道,但下划线像这样的东西应该做的伎俩:

var arr = [ 
    {'date' : 'date', notifications:[{notificationID:4, name: 'abc' }, {notificationID:1, name: 'abc' }]}, 
    {'date' : 'date', notifications:[{notificationID:3, name: 'abc' }, {notificationID:4, name: 'abc' }]} 
]; 

var min = arr.reduce(function (a, b) { 
    return Math.min(a, b.notifications.reduce(function (a, b) { 
    return Math.min(a, b.notificationID); 
    }, Infinity)); 
}, Infinity); 

希望这有助于!