Skip to content

数组工具 (Array)

@pt/utils/modules/array 提供了数组处理相关的工具函数。

unique

数组去重。

typescript
import { unique } from '@pt/utils/modules/array';

const arr = [1, 2, 2, 3, 3, 4];
unique(arr); // [1, 2, 3, 4]

groupBy

数组分组。

typescript
import { groupBy } from '@pt/utils/modules/array';

const users = [
  { age: 20, name: 'John' },
  { age: 20, name: 'Jane' },
  { age: 30, name: 'Bob' }
];

const grouped = groupBy(users, user => user.age);
// {
//   20: [{ age: 20, name: 'John' }, { age: 20, name: 'Jane' }],
//   30: [{ age: 30, name: 'Bob' }]
// }

intersection

数组交集。

typescript
import { intersection } from '@pt/utils/modules/array';

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];
intersection(arr1, arr2); // [3, 4]

最佳实践

  1. 使用按需导入减小打包体积:
typescript
// 推荐
import { formatDate } from '@pt/utils/modules/date';

// 不推荐
import { formatDate } from '@pt/utils';

Released under the MIT License.