mirror of
https://github.com/KieSun/all-of-frontend.git
synced 2024-11-26 00:38:13 +08:00
71 lines
1.6 KiB
Markdown
71 lines
1.6 KiB
Markdown
```js
|
|
/**
|
|
* @param input
|
|
* @param size
|
|
* @returns {Array}
|
|
*/
|
|
_.chunk(['a', 'b', 'c', 'd'], 2)
|
|
// => [['a', 'b'], ['c', 'd']]
|
|
|
|
_.chunk(['a', 'b', 'c', 'd'], 3)
|
|
// => [['a', 'b', 'c'], ['d']]
|
|
|
|
_.chunk(['a', 'b', 'c', 'd'], 5)
|
|
// => [['a', 'b', 'c', 'd']]
|
|
|
|
_.chunk(['a', 'b', 'c', 'd'], 0)
|
|
// => []
|
|
```
|
|
|
|
这道题目其实就是让大家实现一个 lodash 里的函数,这边我们需要注意的一个点是不能更改原数组,虽然题目没有提到,但是我们得想到这个。
|
|
|
|
笔者这里推荐几个答案,分别是不同的写法,难度从低到高吧。
|
|
|
|
首先是遍历的写法:
|
|
|
|
[答案链接](https://github.com/KieSun/fucking-frontend/issues/8#issuecomment-799053150)
|
|
|
|
```js
|
|
function chunk(arr, num) {
|
|
if (num === 0) return [];
|
|
if (Array.isArray(arr) && typeof num === "number") {
|
|
let result = [];
|
|
let i = 0;
|
|
while (i < arr.length) {
|
|
result.push(arr.slice(i, i + num));
|
|
i += num;
|
|
}
|
|
return result;
|
|
} else {
|
|
console.log("params type error");
|
|
}
|
|
}
|
|
```
|
|
|
|
我们也可以使用 `reduce` 来解题:
|
|
|
|
[答案链接](https://github.com/KieSun/fucking-frontend/issues/8#issuecomment-799021398)
|
|
|
|
```js
|
|
const chunk = (arr, len) => arr.reduce((pre, cur, index) => {
|
|
if (index % len === 0) {
|
|
pre.push([cur])
|
|
return pre
|
|
}
|
|
const temp = pre[pre.length - 1]
|
|
temp && temp.push(cur)
|
|
return pre
|
|
}, [])
|
|
```
|
|
|
|
甚至直接优化到一行:
|
|
|
|
[答案链接](https://github.com/KieSun/fucking-frontend/issues/8#issuecomment-799344324)
|
|
|
|
```js
|
|
function chunk(arr, size){
|
|
return Array.from({length: (size = Number.parseInt(size)) ? Math.ceil(arr.length/size) : 0})
|
|
.map((a,i) => arr.slice(i*size, (i+1)*size))
|
|
}
|
|
```
|