Skip to content

数组

随机值

用于数组的随机,将一个全部是数字的数组进行打乱。

用法:

js
import { random } from '@niu-tools/core/array'

random([1, 2, 3])
// [3,1,2]
import { random } from '@niu-tools/core/array'

random([1, 2, 3])
// [3,1,2]
random源码
ts
function random(arr: any[]) {
    return arr.sort(() => Math.random() - 0.5)
}
function random(arr: any[]) {
    return arr.sort(() => Math.random() - 0.5)
}

去重

数组去重

用法:

js
import { uniq } from '@niu-tools/core/array'

uniq([1, 1, 2, 3, 'aa', 'aa'])
// [1,2,3,'aa']
import { uniq } from '@niu-tools/core/array'

uniq([1, 1, 2, 3, 'aa', 'aa'])
// [1,2,3,'aa']
uniq源码
ts
function uniq(arr: any[]) {
    return Array.from(new Set(arr))
}
function uniq(arr: any[]) {
    return Array.from(new Set(arr))
}

数组拍平

数组拍平,将深层的数组排成一维数组

用法:

js
import { demote } from '@niu-tools/core/array'

demote([1, 2, [3, 'aa', ['bb'], [false, ['ddd']]]])
// [1, 2, 3, 'aa', 'bb', false, 'ddd']
import { demote } from '@niu-tools/core/array'

demote([1, 2, [3, 'aa', ['bb'], [false, ['ddd']]]])
// [1, 2, 3, 'aa', 'bb', false, 'ddd']
demote源码
ts
function demote(arr: any[], result: any[] = []) {
    arr.forEach((i) => (isArray(i) ? demote(i, result) : result.push(i)))
    return result
}
function demote(arr: any[], result: any[] = []) {
    arr.forEach((i) => (isArray(i) ? demote(i, result) : result.push(i)))
    return result
}

源码

查看源码
array/index.ts源码
ts
import { isArray } from '../utils'

//random===== Start
function random(arr: any[]) {
    return arr.sort(() => Math.random() - 0.5)
}
//random===== End

//uniq===== Start
function uniq(arr: any[]) {
    return Array.from(new Set(arr))
}
//uniq===== End

//demote===== Start
function demote(arr: any[], result: any[] = []) {
    arr.forEach((i) => (isArray(i) ? demote(i, result) : result.push(i)))
    return result
}
//demote===== End

export { random, uniq, demote }
import { isArray } from '../utils'

//random===== Start
function random(arr: any[]) {
    return arr.sort(() => Math.random() - 0.5)
}
//random===== End

//uniq===== Start
function uniq(arr: any[]) {
    return Array.from(new Set(arr))
}
//uniq===== End

//demote===== Start
function demote(arr: any[], result: any[] = []) {
    arr.forEach((i) => (isArray(i) ? demote(i, result) : result.push(i)))
    return result
}
//demote===== End

export { random, uniq, demote }

Released under the MIT License.