第1引数「配列(Object)」の各値を第2引数の関数の条件によって振り分ける。
■使用例
var arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
var func = function( val ){
return val % 2 == 0;
};
// re = [ [2,4,6,8,10], [1,3,5,7,9] ];
var re = _.partition( arr, func );
var obj = [
{
title : "Final Fantasy4 Original SoundTrack",
year : 1991,
author : "Nobuo Uematu"
},
{
title : "Final Fantasy5 Original SoundTrack",
year : 1992,
author : "Nobuo Uematu"
},
{
title : "Final Fantasy6 Original SoundTrack",
year : 1992,
author : "Nobuo Uematu"
},
{
title : "悪魔城ドラキュラX 月下の夜想曲",
year : 1994,
author : "Michiru Yamane"
}
];
var func = function( obj ){
return obj.year == 1992;
}
// re = [[
{"title":"Final Fantasy5 Original SoundTrack","year":1992,"author":"Nobuo Uematu"},
{"title":"Final Fantasy6 Original SoundTrack","year":1992,"author":"Nobuo Uematu"}
],[
{"title":"Final Fantasy4 Original SoundTrack","year":1991,"author":"Nobuo Uematu"},
{"title":"悪魔城ドラキュラX 月下の夜想曲","year":1994,"author":"Michiru Yamane"}
]];
var re = _.partition( obj, func );
■内部構造
_.partition = function(obj, predicate, context) {
// 第3引数が入力されていない、第2引数が関数ならそのまま。
predicate = cb(predicate, context);
var pass = [], fail = [];
// 第1引数「配列(Object)」の各値を第2引数の関数の条件によって振り分ける。
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};