js converts a multidimensional array into a one-dimensional array and then reorders it

js converts a multidimensional array into a one-dimensional array and then reorders it

Organize a few methods, in case you forget them later and have to look through your notes again

Let's talk about flattening multidimensional arrays 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)); // Specify the number of nested levels // 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 levels of nesting there are, // Output: [ 1, 1, 2, 4, 2, 1, 3, 4, 2, 1, 5, 2, 5, 3 ]

Method 2: Concatenate with empty strings and then split with split()

Lazy writing

// Still this array let arr = [1, 1, 2, [4, 2, [1, 3, [4, 2, 1]], 5], 2, 5, 3]
// When characters are operated with other basic data types, they will all be converted into characters. 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 is not very good, let's continue to optimize it // Still using 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 we can convert arrays into character types through calculations, using arr+' ' does not seem so elegant. At this time, I suddenly remembered that the js Number object has a toString() method.

Definition and Usage
The toString() method converts a Number object to 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 an array into a string.
Elements are separated by the specified delimiter.

By calling the join() method of an array, a string is returned. Each element in arr is converted to a string. Elements can be concatenated by passing a separator symbol. The default separator is comma.

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 talking about recursion, we have to mention, what is recursion?
The so-called recursive function is to call the function in the function body. When using recursion, be careful to avoid dead loops.

definition:
A recursive function is a function that calls itself within its body.
When using recursive functions, pay attention to the function termination conditions to avoid infinite loops;

The recursion probably looks like this:

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

Flatten a multidimensional array:

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++) {
        // Determine if the traversed value is still an array and continue traversing if (Array.isArray(arr[i])) { // Use array 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: Using reduce

This method must be learned and will be used frequently in Vue later.

reduce
The first parameter: represents the previous value (initial value) (previousValue)
The second parameter: represents the current value (currentValue)
The third parameter: represents the current index value (currentIndex)
The fourth parameter: represents the array currently traversed

initialValue: You can manually assign an initial value. Return value: The return value in the current loop can be used as the initialization for the next loop.

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

Array deduplication

Method 1: Create a new array and check whether the element exists in the new array. If not, add the 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 the 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 the data is expanded and stored in the array const newArr = [...new Set(arr)]
console.log(newArr);

// Alternatively, you can use the Array.from() method to convert an array-like object or a traversable object into a real array.
const newArr = Array.from(new Set(arr))
console.log(newArr);

Method 3: Using 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 subsequent duplicate values ​​is not equal to the position returned by indexOf and will be filtered out by filter})
console.log(newArr);

Sorting an Array

Method 1: Using sort()

Definition and Usage
The sort() method is used to sort the elements of an array.

grammar
arrayObject.sort(sortby)

Return value A reference to the array. Note that the array is sorted on the original array and no copies are made.

Description If this method is called without parameters, the elements in the array will be sorted in alphabetical order, or more precisely, in the order of character encodings. To do this, first convert the array elements to strings (if necessary) so that they can be compared.
If you want to sort by some other criterion, you need to provide a comparison function that compares two values ​​and returns a number that describes the relative order of the two values. The comparison function should have two parameters a and b and return the following value:

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 is equal to b, return 0.
If a is greater than b, returns a value greater than 0.

parameter describe
sortby Optional. Specifies 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));

This is the end of this article about how to convert a multidimensional array into a one-dimensional array and then remove the reordering in js. For more related content about how to convert a multidimensional array into a one-dimensional array and remove the reordering in js, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • In-depth study of JavaScript array deduplication problem
  • JavaScript array deduplication solution
  • Detailed explanation of several methods of deduplication in Javascript array
  • Detailed explanation of JavaScript array deduplication
  • JavaScript commonly used array deduplication actual combat source code
  • Examples and comparison of 3 methods for deduplication of JS object arrays
  • Detailed discussion of several methods for deduplicating JavaScript arrays

<<:  Complete steps to set up automatic updates in CentOS 8

>>:  Tutorial on installing mysql under centos7

Recommend

How to implement page jump in Vue project

Table of contents 1. Create a vue-cli default pro...

How to switch directories efficiently in Linux

When it comes to switching directories under Linu...

Install MySQL in Ubuntu 18.04 (Graphical Tutorial)

Tip: The following operations are all performed u...

Does Mysql ALTER TABLE lock the table when adding fields?

Table of contents Before MySQL 5.6 After MySQL 5....

Detailed explanation of Nginx passively checking the server's survival status

introduce Monitors the health of HTTP servers in ...

Background gradient animation effect made by css3

Achieve results Implementation Code html <h1 c...

MySQL InnoDB row_id boundary overflow verification method steps

background I talked to my classmates about a boun...

A brief discussion on what situations in MySQL will cause index failure

Here are some tips from training institutions and...

MySQL foreign key setting method example

1. Foreign key setting method 1. In MySQL, in ord...

Vue3.0 uses the vue-grid-layout plug-in to implement drag layout

Table of contents 1. Plugins 2. Interlude 3. Impl...

How to notify users of crontab execution results by email

symptom I set a crontab task on a centos7 host, b...

7 Ways to Write a Vue v-for Loop

Table of contents 1. Always use key in v-for loop...

How to Rename Multiple Files at Once in Linux

Preface In our daily work, we often need to renam...