JS convert multi-dimensional array to one-dimensional array and reorder it

Time:2021-11-27

Organize a few methods for fear of forgetting and turning notes everywhere


Let’s talk about multidimensional array flattening first

Method 1: flat ()

//For example, here is a multidimensional array
let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
console.log(arr.flat(2)); //  Specifies the number of nested layers
//Output [1, 1, 2, 4, 2, 1, 3, [4, 2, < 1 empty item >, 1], 5, 2, 5, 3]

console.log(arr.flat(Infinity)); //  No matter how many layers are nested
//Output [1, 1, 2, 4, 2, 1, 3, 4, 2, 1, 5, 2, 5, 3]

Method 2: splice empty strings and split them with split()

Lazy writing

//Or this array
let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
//Character type and other basic data types will become character type when they are operated, and then call the split () method to split them with ','
console.log((arr + '').split(','));
//Output ['1', '1', '2', '4', '2', '1', '3', '4', '2', '1', '5', '2', '5', '3']

//The output result is not particularly good-looking. Continue to optimize it
//Or this array
let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
let newArr = (arr + '').split(',')
let arr1 = []
newArr.forEach((items) => {
    Arr1.push (+ items) // '+ items' convert data type
})
console.log(arr1);
//Output [1, 1, 2, 4, 2, 1, 3, 4, 2, 1, 5, 2, 5, 3]

Method 3: tostring()

Since you can convert an array into a character type by operation, usearr+' 'It really doesn’t look so elegant. At this time, it suddenly occurred to me that the JS number object has a toString () method

Definition and Usage

The toString () method converts a number object into a string and returns the result.

let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
let newArr = arr.toString().split(',')
let arr1 = []
newArr.forEach((items) => {
    arr1.push(+items)
})
console.log(arr1);
//Output ['1', '1', '2', '4', '2', '1', '3', '4', '2', '1', '5', '2', '5', '3']

Method 4: join ()

Definition and Usage

The join () method is used to put all the elements in the array into a string.
Elements are separated by a specified separator.

By calling the join () method of the array, you can return a string and convert each element in the ARR into a string. You can concatenate elements by passing a division symbol, which is separated by commas by default

let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
let newArr = arr.join().split(',')
console.log(newArr)
//Output ['1', '1', '2', '4', '2', '1', '3', '4', '2', '1', '5', '2', '5', '3']

Method 5: recursive call

When it comes to recursion, I have to mention, what is recursion?
The so-called recursive function is to call this function in the function body. When using recursion, pay attention to avoid dead loop

definition:

Recursive function is to call this function in the function body;
When using recursive functions, pay attention to the function termination conditions to avoid dead loops;

Recursion looks like this:

function a() {
    if (a <= 1) {
        return 1
    } else {
        return a * fn(a - 1)
    }
}

Realize multi-dimensional array flattening:

let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
let newArr = []

let fn = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        //Judge that if the traversed value is still an array, continue to traverse
        If (array. Isarray (array [i]) {// use array. Isarray() to determine whether the passed value is an array
            fn(arr[i])
            //If the traversed value is not an array, push it into the new array newarr
        } else {
            newArr.push(arr[i])
        }
    }
}
fn(arr)
console.log(newArr);

Method 6: use reduce

This method must be learned and will be often used in later Vue

reduce

The first parameter: indicates the previous value (initial value) (previousvalue)
The second parameter: represents the current value
The third parameter: indicates the current index value (currentindex)
The fourth parameter: indicates the currently traversed array

Initialvalue: you can assign an initial value manually
Return value: the return value in the current cycle, which can be used as the initialization of the next cycle

const arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
const fn = (array) => {
    return array.reduce((prev, curr) => {
        //Determine whether curr is an array
        return prev.concat(Array.isArray(curr) ? fn(curr) : curr)
    }, [])
}
console.log(fn(arr))

Array de duplication

Method 1: create a new array and judge whether the element exists in the new array. If it does not exist, add this element to the new array

const arr = [1, 1, 2, 4, 2, 1, 3, 4, 2, 1, 5, 2, 5, 3]
const fn = (arr) => {
    const newArr = []
    for (let i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) == -1) {
            newArr.push(arr[i])
        }
    }
    return newArr
}
console.log(fn(arr));

Method 2: use set method

const arr = [1, 1, 2, 4, 2, 1, 3, 4, 2, 1, 5, 2, 5, 3]
//Using the set data structure provided by ES6, the new set members are unique, and then expand the data and save it into the array
const newArr = [...new Set(arr)]
console.log(newArr);

//Or you can use the array. From () method to convert a class array object or traversable object into a real array.
const newArr = Array.from(new Set(arr))
console.log(newArr);

Method 3: use filter ()

const arr = [1, 1, 2, 4, 2, 1, 3, 4, 2, 1, 5, 2, 5, 3]
Const newarr = arr.filter ((value, index, array) = > {// pass three parameters: value, index and original array
    Return array. Indexof (value) = = index // indexof always returns the index of the first value. The index of the following repeated values is not in the same position as that returned by indexof and will be filtered out by the filter
})
console.log(newArr);

Array sorting

Method 1: use sort()

Definition and Usage

The sort () method is used to sort the elements of the array.

grammar

arrayObject.sort(sortby)

Return value

A reference to an array. Note that the array is sorted on the original array and does not generate a copy.

explain

If no parameters are used when calling this method, the elements in the array will be sorted alphabetically. To be more precise, they will be sorted in the order of character encoding. To achieve this, you should first convert the elements of the array into strings (if necessary) for comparison.
If you want to sort according to other criteria, you need to provide a comparison function, which compares two values and returns a number indicating the relative order of the two values. The comparison function should have two parameters a and B, and its return values are as follows:

  • If a is less than B, a should appear before B in the sorted array, and a value less than 0 is returned.
  • If a equals B, 0 is returned.
  • If a is greater than B, a value greater than 0 is returned.
parameter describe
sortby Optional. Specify the sort order. Must be a function.
const arr = [1, 23, 1, 1, 1, 3, 23, 5, 6, 7, 9, 9, 8, 5, 5, 5];
const fn = (a, b) => {
    Return a - B // B - A in reverse order
}
console.log(arr.sort(fn));