underScore.js의 collection 중에서 _.filter() 함수에 대해 알아보자.
filter _.filter(list, predicate, [context])
list: collection으로써, 배열이나 객체가 될 수 있다.
predicate : list의 각 element(value)의 결과값이 truth인지 확인하는 test 함수이다.
[context] : predicate 함수에서 this로 바인딩 되는 것이다.(optional)
→ list의 각 element(value)를 predicate 함수를 돌려, 값이 truth인 것만 배열의 element로 리턴한다.
// list가 배열일 경우
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) {
return num % 2 == 0;
});
console.log(evens); // [2, 4, 6]
// 배열 [1, 2, 3, 4, 5, 6]의 각 element가 test 함수의 num의 인자로 하나씩 들어가, 결과 값이 truth인 값만 모아 배열의 형태로 출력된다.
// list가 객체일 경우
var obj = {"a": 1, "b": 2, "c": 3, "d":4}
var evens = _.filter(obj, function(num) {
return num % 2 == 0;
});
console.log( evens ); // [2, 4]
// 객체 obj의 각 value가 test 함수의 num의 인자로 하나씩 들어가, 결과 값이 truth인 값만 모아 배열의 형태로 출력된다.
A = [5, 7, 10, 15];
var divideBy5 = _.filter([0,1,2,3], function(item) {
return this[item] % 5 == 0 ;
}, A)
console.log(divideBy5); // [0, 2, 3]
// 배열 [0,1,2,3]의 각 element가 test 함수의 item의 인자로 하나씩 들어가, 결과 값이 truth인 값만 모아 배열로 출력되는데, 이때 [context]로 사용된 A는 test 함수안에 있는 this로 바인딩 되어 사용된다.
_.filter() 함수를 직접 구현
<알고리즘>
_.filter = function (collection, test) {
let result = [];
_.each(collection, function(elm) {
if(test(elm)) {
result.push(elm);
}
});
return result;
};