2014-06-20 125 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); 

希望這有助於!