UNPKG

own-js

Version:

自家前端交流在项目开发中构建的JS工具库,内含项目中最常用的JS工具函数

68 lines (63 loc) 2.03 kB
/** * 对多个数组合并去重 * 数组支持数字,字符串。 * @returns {*[]} */ export const combineDistinct = (...arr: any[]): any[] => { const arrAll = [].concat.apply([], arr) return Array.from(new Set(arrAll)) } /** * 对象数组,根据对象的某个字段进行去重 * @param source 原始数组 * @param property 属性名 */ export const arrayDistinct = (source: any[], property: string): any[] => { const tempMap = new Map() return source.filter(a => !tempMap.has(a[property]) && tempMap.set(a[property], 1)) } /** * 对某个对象数组按照某个字段来排序 * @param property 排序字段 * @param isAsc 排序方式,默认升序 * @returns {function(*, *)} */ export const sortBy = (property: string, isAsc: boolean = true): any => { //根据传过来的字段进行排序 return (x: any, y: any): number => { return isAsc ? x[property] - y[property] : y[property] - x[property] } } /** * 数组按照属性分组 * @param source 数组 * @param property 属性名 */ export const groupBy = (source: any[], property: string) => { return source.reduce(function (acc, obj) { let key = obj[property] if (!acc[key]) { acc[key] = [] } acc[key].push(obj) return acc }, {}) } /** * 过滤数组(支持递归过滤) * 根据 filters 过滤条件 从 source 取值 * 例如:查找权限,从所有权限项中(source)中找到含有张三的权限(filters)的项 * @param source 原始数组 * @param filters 过滤条件['k1','k2','k3'] * @param property 过滤属性 * @param children 子集的属性名 */ export const filterBy = (source: any[], filters: any[], property: string, children: string): any[] => { return source.filter(m => { // 没有子集可以把这个if去掉 if (children && m[children]) { m.children = filterBy(m.children, filters, property, children) } return filters.some(p => p === m.permission) }) }