_.zip()
import _ from "lodash";
const list1 = ['a', 'b']
const list2 = [1, 2];
const list3 = [true, false];
/**
* 1. Lodash zip()
*/
const lodashZip = _.zip(list1, list2, list3);
console.log(lodashZip); // [ [ 'a', 1, true ], [ 'b', 2, false ] ]
/**
* 2. myZip() 구현
*/
function myZip(...arr) {
let zipResult = [];
// [0, 0], [1, 0], [2, 0] -> [0, 1], [1, 1], [2, 1]
for(let i = 0; i < arr.length-1; i++) {
let zip = [];
for (let j = 0; j < arr.length; j++) {
zip.push(arr[j][i]);
}
zipResult.push(zip);
}
return zipResult;
}
const zipResult = myZip (list1, list2, list3);
console.log(zipResult);
_.unzip()
/**
* 3. Lodash unZip()
*/
const lodashUnzip = _.unzip([['a', 1, true], ['b', 2, false]]);
console.log(lodashUnzip); // [ [ 'a', 'b' ], [ 1, 2 ], [ true, false ] ]
/**
* 4. myUnzip() 구현
*/
function myUnzip([...arr]) {
let unZipResult = [];
let zippedArr = [...arr]; // ...arr :: [ [ 'a', 1, true ], [ 'b', 2, false ] ]
// unzip 결과 :: [['a', 'b'], [1, 2], [true, false]]
// [[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]
for(let i = 0; i <= zippedArr.length; i++) { // zippedArr[i].length = 3
let unZip = [];
for (let j = 0; j < zippedArr.length; j++) { // zippedArr.length = 2
unZip.push(zippedArr[j][i]);
}
unZipResult.push(unZip);
}
return unZipResult;
}
const unZipResult = myUnzip ([['a', 1, true], ['b', 2, false]]);
console.log(unZipResult);
'개발 > lodash' 카테고리의 다른 글
lodash :: _.uniq(array) 구현하기 (0) | 2023.10.08 |
---|