reducedFilter - 배열 필터링
const reducedFilter = (data, keys, fn) => data.filter(fn).map(el => keys.reduce((acc, key) => { acc[key] = el[key]; return acc; }, {}) ); const data = [ { id: 1, name: 'john', age: 24 }, { id: 2, name: 'mike', age: 50 } ]; reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
pull - 선택 값 골라내기
const pull = (arr, ...args) => { let argState = Array.isArray(args[0]) ? args[0] : args; let pulled = arr.filter((v, i) => !argState.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]
mapObject - 배열 -> map
const mapObject = (arr, fn) => (a => ( (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) ))(); const squareIt = arr => mapObject(arr, a => a * a); squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
join - 배열 구분자
const join = (arr, separator = ',', end = separator) => arr.reduce( (acc, val, i) => i === arr.length - 2 ? acc + val + end : i === arr.length - 1 ? acc + val : acc + val + separator, '' ); join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen" join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen" join(['pen', 'pineapple', 'apple', 'pen']); // ..
countBy - 그룹별 카운트
const countBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => { acc[val] = (acc[val] || 0) + 1; return acc; }, {}); countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2} countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}