Array to heavy

  • forCirculation +indexOf
    function unique(arr) {
        let uniqueArr = []
        const len = arr.length
        for (let i = 0; i < len; i++) {
            if (uniqueArr.indexOf(arr[i]) == -1) {
                uniqueArr.push(arr[i])
            }
        }
        return uniqueArr
    }
    const arr = [1.2.1.3.'1'.2.3.4]
    const result = unique(arr)
    console.log(result) // [1, 2, 3, '1', 4]
    Copy the code
  • Sort and de-weight
    function unique(arr) {
        let uniqueArr = []
        let sortArr = arr.concat().sort()
        let len = sortArr.length
        let prev
        for (let i = 0; i < len; i++) {
            if(! i || prev ! == sortArr[i]) { uniqueArr.push(sortArr[i]) } prev = sortArr[i] }return uniqueArr
    }
    const arr = [1.2.1.3.'1'.2.3.4]
    const result = unique(arr)
    console.log(result) // [1, '1', 2, 3, 4]
    Copy the code
  • Hash table
    function unique(arr) {
        let uniqueArr = []
        let obj = {}
        const len = arr.length
        for (let i = 0; i < len; i++) {
            obj[typeof arr[i] + arr[i]] = arr[i]
        }
        for (let i in obj) {
            uniqueArr.push(obj[i])
        }
        return uniqueArr
    }
    const arr = [1.2.1.3.'1'.2.3.4]
    const result = unique(arr)
    console.log(result) // [1, 2, 3, '1', 4]
    Copy the code
  • usingsetstructure
    function unique(arr) {
        return Array.from(new Set(arr))
    }
    const arr = [1.2.1.3.'1'.2.3.4]
    const result = unique(arr)
    console.log(result) // [1, 2, 3, '1', 4]
    Copy the code

Array flattening

  • The recursive traversal
    function flatten(array, dep = 1) {
        let result = []
        for(let i = 0; i < array.length; i++) {
            if(dep > 0) {
                if(Array.isArray(array[i])){
                    result = result.concat(flatten(array[i], dep - 1))}else {
                    result.push(array[i])
                } 
            }else {
                result.push(array[i])
            }
        }
        return result
    }
    const arr = [1[2[3.4]],5.6]
    const result = flatten(arr)
    console.log(result) // [1, 2, [3, 4], 5, 6]
    Copy the code
  • An array offlatmethods
    function flatten(array) {
        return array.flat(Infinity)}const arr = [1[2[3.4]],5.6]
    const result = flatten(arr)
    console.log(result) // [1, 2, 3, 4, 5, 6]
    Copy the code

    flatThe method takes an argument representing the number of layers you want to flatten, which defaults to 1

  • Extended operator
    function flatten(array, dep = 1) {
        while (array.some(item= > Array.isArray(item)) && dep > 0) { dep-- array = [].concat(... array); }return array
    }
    const arr = [1[2[3.4]],5.6]
    const result = flatten(arr)
    console.log(result) // [1, 2, [3, 4], 5, 6]
    Copy the code
  • usingreduce
    function flatten(array, dep = 1) {
        let result = []
        if (dep > 0) {
            result = array.reduce((total, value) = > {
                return total.concat(Array.isArray(value) ? flatten(value, dep - 1) : value)
            }, [])
        } else {
            result = array.slice()
        }
        return result
    }
    const arr = [1[2[3.4]],5.6]
    const result = flatten(arr)
    console.log(result) // [1, 2, [3, 4], 5, 6]
    Copy the code

A random arrangement of arrays

The random arrangement of arrays is like shuffling cards

function shuffle(array) {
    const len = array.length
    for (let i = len - 1; i > 0; i--) {
        const randomIndex = Math.floor(Math.random() * (i + 1)) 
        swap(array, i, randomIndex)
    }
}
Copy the code

reduce

  • demo
    const res = [1.2.3.4.5].reduce(function (a, b, i) {
        return a + b;
    })
    console.log(res) / / 15
    const res1 = [1.2.3.4.5].reduce(function (a, b, i) {
        return a + b;
    }, 10);
    console.log(res1) / / 25
    Copy the code
  • Analog implementation
    Array.prototype.reduce = function(callback, total) {
        const array = this
        if (array.length === 0 && arguments.length < 2) {
            throw new Error('TypeError: Reduce of empty array with no initial value')}let startIndex
        let result
        if (arguments.length >= 2) {
            startIndex = 0
            result = total
        }else {
            startIndex = 1
            result = array[0]}for (let i = startIndex; i < array.length; i++) {
            result = callback(result, array[i], i, array)
        }
        return result
    }
    Copy the code

Commonly used method

  • A static method
    • Array.isArray()Returns a Boolean value indicating whether the argument is an array
    • Array.from()Used to turn two classes of objects into true arrays: array-like objects and iterable objects (sets and maps).
    • Array.of()Used to convert a set of values into an array
  • Change the original array
    • push()Adds one or more elements to the end of the array
    • pop()Removes and returns the last element of the array
    • unshift()Adds one or more elements to the beginning of an array
    • shift()Removes and returns the first element of the array
    • reverse()Reverses the order of the elements in an array
    • splice()Removes a part of the original array and can add a new array member at the deleted location
    • sort()Sort the elements of an array, by default, in lexicographical order
    • fill()The fill method fills an array with the given value
  • Do not change the original array
    • concat()Used to merge multiple arrays and return a new array
    • slice()Retrieves part of the target array and returns a new array
    • join()Returns all array members concatenated as a string, separated by commas by default, with the specified argument as the delimiter
    • map()Pass all the members of the array to the argument function, and return the result of each execution as a new array
    • forEach()Executes the argument function on all the members of the array, returning no value
    • filter()Used to filter the members of an array. The members that meet the criteria are returned as a new array
    • every()All members return true, and the entire every method returns true
    • some()As long as one member returns true, the entire some method returns true
    • keys().values().entries()For traversing a number group, usefor of
    • reduce()Each member of the array is processed from left to right, eventually accumulating to a value
    • reduceRight()Each member of the array is processed from right to left, eventually accumulating to a value
    • indexOf()Returns the position of the given element’s first occurrence in the array, or -1 if none. NaN cannot be searched
    • lastIndexOf()Returns the last occurrence of the given element in the array, or -1 if none occurred
    • find()Used to find the first qualified array member, or return undefined if none exists
    • findIndex()Returns the position of the first qualified array member, or -1 if all members do not
    • includes()Returns a Boolean value indicating whether an array contains a given value
    • flat()Used to “flatten” a nested array into a one-dimensional array. This method returns a new array with no effect on the original data

More articles

  • Dumb blog