IT评测·应用市场-qidao123.com技术社区

标题: 在js中数组相关用法解说 [打印本页]

作者: 没腿的鸟    时间: 2025-4-6 19:18
标题: 在js中数组相关用法解说
数组

uniqueArray

简单数组去重
  1. /**
  2. * 简单数组去重
  3. * @param arr
  4. * @returns
  5. */
  6. export const uniqueArray = <T>(arr: T[]) => [...new Set(arr)];
  7. const arr1 = [1,1,1,1 2, 3];
  8. uniqueArray(arr); // [1,2,3]
复制代码
uniqueArrayByKey

根据 key 数组去重
  1. /**
  2. * 根据key数组去重
  3. * @param arr
  4. * @param key
  5. * @returns
  6. */
  7. export function uniqeArrayByKey(arr: any[], key: string) {
  8.   const obj: Record<string, any> = {}
  9.   return arr.reduce((prev, item) => {
  10.     obj[item[key]] ? '' : (obj[item[key]] = true && prev.push(item))
  11.     return prev
  12.   }, [])
  13. }
  14. const arr = [
  15.   { id: 1, parentid: 0 },
  16.   { id: 2, parentid: 1 },
  17.   { id: 3, parentid: 1 },
  18.   { id: 3, parentid: 1 },
  19. ]
  20. uniqeArrayByKey(arr, 'id')
  21. /**
  22. * [
  23.   { id: 1, parentid: 0 },
  24.   { id: 2, parentid: 1 },
  25.   { id: 3, parentid: 1 },
  26. ];
  27. *
  28. */
复制代码
sortCompare

数组根据 key 排序
  1. /**
  2. * 排序
  3. * arr: 所需排序的数组
  4. * prop:排序的依据字段
  5. * order:默认true -> 正序(小 -> 大) / false -> 倒序(大 -> 小)
  6. */
  7. export const sortCompare = (arr: any[], prop: string | number, order = true) => {
  8.   return arr.sort(compare(prop, order))
  9. }
  10. function compare(prop: string | number, order: boolean) {
  11.   return (obj1: Record<string, any>, obj2: Record<string, any>) => {
  12.     let val1 = obj1[prop]
  13.     let val2 = obj2[prop]
  14.     if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
  15.       val1 = Number(val1)
  16.       val2 = Number(val2)
  17.     }
  18.     if (order) {
  19.       if (val1 < val2) return -1
  20.       else if (val1 > val2) return 1
  21.       else return 0
  22.     } else {
  23.       if (val1 > val2) return -1
  24.       else if (val1 < val2) return 1
  25.       else return 0
  26.     }
  27.   }
  28. }
  29. const arr = [
  30.   { order: 1, name: '1' },
  31.   { order: 10, name: '10' },
  32.   { order: 3, name: '3' },
  33. ]
  34. const sortArr = sortCompare(arr, order)
  35. /**
  36. * [
  37.   { order: 1, name: '1' },
  38.   { order: 3, name: '3' },
  39.   { order: 10, name: '10' },
  40. ];
  41. *
  42. */
复制代码
multiFieldSort

数组根据多个字段排序
  1. /**
  2. * multiFieldSort(data, [{ field: 'age', order: 'desc' }, { field: 'name' }, { field: 'salary', order: 'desc' }])
  3. * @param {*} arr
  4. * @param {*} sortFields
  5. * @returns
  6. */
  7. export function multiFieldSort(arr, sortFields) {
  8.   return arr.sort((a, b) => {
  9.     for (let i = 0; i < sortFields.length; i++) {
  10.       let field = sortFields[i].field
  11.       let order = sortFields[i].order || 'asc'
  12.       if (a[field] < b[field]) {
  13.         return order === 'asc' ? -1 : 1
  14.       }
  15.       if (a[field] > b[field]) {
  16.         return order === 'asc' ? 1 : -1
  17.       }
  18.     }
  19.     return 0
  20.   })
  21. }
复制代码
getArrayLabelByValue

根据数组和 value 获取数组中的 label,没有返回 undefined
  1. interface IParams {
  2.   arr: any[]
  3.   value: any
  4.   valueKey?: string
  5.   labelKey?: string
  6.   defaultValue?: string | number
  7. }
  8. /**
  9. * 根据数组获取数组中的值
  10. * @param param
  11. * @returns
  12. */
  13. export function getArrayLabelByValue({
  14.   arr,
  15.   value,
  16.   valueKey = 'value',
  17.   labelKey = 'label',
  18.   defaultValue = undefined,
  19. }: IParams) {
  20.   if (!Array.isArray(arr)) {
  21.     throw new Error('Type requires an array')
  22.   }
  23.   const obj = arr.find(item => String(item[valueKey]) === String(value))
  24.   return obj ? obj[labelKey] : defaultValue
  25. }
  26. /**
  27. * {
  28.   arr,
  29.   value,
  30.   valueKey = 'value',
  31.   labelKey = 'label',
  32.   defaultValue = undefined,
  33. }
  34. */
  35. const arr = [
  36.   {
  37.     label: 'Tom',
  38.     value: '1',
  39.   },
  40.   {
  41.     label: 'Lily',
  42.     value: '2',
  43.   },
  44. ]
  45. getArrayLabelByValue({ arr, value: '2' }) // Lily
复制代码
shuffle

洗牌算法随机
  1. /**
  2. * 洗牌算法随机
  3. * @param arr
  4. * @returns
  5. */
  6. export function shuffle(arr: any[]) {
  7.   let result: any[] = [],
  8.     random: number
  9.   while (arr.length > 0) {
  10.     random = Math.floor(Math.random() * arr.length)
  11.     result.push(arr[random])
  12.     arr.splice(random, 1)
  13.   }
  14.   return result
  15. }
  16. const arr = [1, 2, 3]
  17. shuffle(arr) // [2,3,1]
复制代码
compact

去除数组中的无效/无用值
  1. /**
  2. * 去除数组中的无效/无用值
  3. * @param arr
  4. * @returns
  5. */
  6. export function compact(arr: any[]) {
  7.   return arr.filter(Boolean)
  8. }
  9. compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34])
  10. // [ 1, 2, 3, 'a', 's', 34 ]
复制代码
countOccurrences

检测数值出现次数
  1. /**
  2. * 检测数值出现次数
  3. * @param arr
  4. * @param val
  5. * @returns
  6. */
  7. export function countOccurrences(arr: any[], val: any) {
  8.   return arr.reduce((a, v) => (v === val ? a + 1 : a), 0)
  9. }
  10. countOccurrences([1, 1, 2, 1, 2, 3], 1) // 3
复制代码
flatten

指定深度扁平化数组
  1. /**
  2. * 指定深度扁平化数组
  3. * @param arr
  4. * @param depth
  5. * @returns
  6. */
  7. export function flatten(arr: any[], depth = 1): any[] {
  8.   return arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), [])
  9. }
  10. flatten([1, [2], 3, 4]) // [1, 2, 3, 4]
  11. flatten([1, [2, [3, [4, 5], 6], 7], 8], 2) // [1, 2, 3, [4, 5], 6, 7, 8]
复制代码
deepFlatten

递归扁平化数组
  1. /**
  2. * 递归扁平化数组
  3. * @param arr
  4. * @returns
  5. */
  6. export function deepFlatten(arr: any[]): any[] {
  7.   return [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)))
  8. }
  9. deepFlatten([1, [2], [[3], 4], 5]) // [1,2,3,4,5]
复制代码
difference

查找两个数组之间的差异
  1. /**
  2. * 查找两个数组之间的差异
  3. * @param a
  4. * @param b
  5. * @returns
  6. */
  7. export const difference = (a: any[], b: any[]) => {
  8.   const s = new Set(b)
  9.   return a.filter(x => !s.has(x))
  10. }
  11. difference([1, 2, 3], [1, 2, 4]) // [3]
复制代码
indexOfAll

返回数组中某值的所有索引
  1. /**
  2. * 返回数组中某值的所有索引
  3. * @param arr
  4. * @param val
  5. * @returns
  6. */
  7. export const indexOfAll = (arr: any[], val: any) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), [])
  8. indexOfAll([1, 2, 3, 1, 2, 3], 1) // [0,3]
  9. indexOfAll([1, 2, 3], 4) // []
复制代码
intersection

两数组的交集
  1. /**
  2. * 两数组的交集
  3. * @param a
  4. * @param b
  5. * @returns
  6. */
  7. export const intersection = (a: any[], b: any[]) => {
  8.   const s = new Set(b)
  9.   return a.filter(x => s.has(x))
  10. }
  11. intersection([1, 2, 3], [4, 3, 2]) // [2, 3]
复制代码
intersectionBy

两数组都符合条件的交集
可用于在对两个数组的每个元素执行了函数之后,返回两个数组中存在的元素列表。
  1. /**
  2. * 两数组都符合条件的交集
  3. * @param a
  4. * @param b
  5. * @param fn
  6. * @returns
  7. */
  8. export const intersectionBy = (a: any[], b: any[], fn: (arg0: any) => unknown) => {
  9.   const s = new Set(b.map(fn))
  10.   return a.filter(x => s.has(fn(x)))
  11. }
  12. intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor) // [2.1]
复制代码
intersectionWith

先比较后返回交集
  1. /**
  2. * 先比较后返回交集
  3. * @param a
  4. * @param b
  5. * @param comp
  6. * @returns
  7. */
  8. export const intersectionWith = (a: any[], b: any[], comp: (arg0: any, arg1: any) => any) =>
  9.   a.filter(x => b.findIndex(y => comp(x, y)) !== -1)
  10. intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)) // [1.5, 3, 0]
复制代码
addDeepProperty

给树结构每一层添加一层 deep 用以区分
  1. export function addDeepProperty(tree, deep = 1) {
  2.   // 添加属性 deep 到当前层级
  3.   tree.deep = deep
  4.   // 递归处理子节点
  5.   if (tree.children && tree.children.length > 0) {
  6.     tree.children.forEach(child => {
  7.       addDeepProperty(child, deep + 1)
  8.     })
  9.   }
  10.   return tree
  11. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4