-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
37 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import get from './get' | ||
import { ToPathValue } from './toPath' | ||
|
||
/** | ||
* 根据 `iteratee` 对 `arr` 进行分组。 | ||
* | ||
* @param arr 要分组的数据 | ||
* @param iteratee 迭代值,字符串或数字表示键路径,函数表示以该函数生成 `key` | ||
* @returns 分组结果 | ||
*/ | ||
export default function groupBy<T>( | ||
arr: T[], | ||
iteratee: ToPathValue | ((item: T, index: number) => any) | ||
): { [key: string]: T[] } { | ||
const iterateeIsFunction = typeof iteratee === 'function' | ||
return arr.reduce<{ [key: string]: T[] }>((res, item, index) => { | ||
const key = iterateeIsFunction | ||
? (iteratee as any)(item, index) | ||
: get(item as any, iteratee as any) | ||
if (!res[key]) { | ||
res[key] = [] | ||
} | ||
res[key].push(item) | ||
return res | ||
}, {}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters