js implements array flattening

js implements array flattening

How to flatten an array

What is array flattening?

Array flattening : refers to converting a multidimensional array into a one-dimensional array.

Example: Flatten the following array.

const arr = [1, [2, 3, [4, 5]]] // ---> [ 1, 2, 3, 4, 5 ]

1. Using flat()

The flat() method was proposed by ES10. It recursively traverses the array at a specified depth and merges all elements with the elements in the traversed sub-array into a new array and returns it. (flat means "horizontal; flat")

const result1 = arr.flat(Infinity) // specifies the depth to be infinite console.log(result1) // [ 1, 2, 3, 4, 5 ]
const result2 = arr.flat(1) // Specify depth as 1
console.log(result2) // [ 1, 2, 3, [ 4, 5 ] ]
const result3 = arr.flat(2) // specifies the depth to be 2
console.log(result3) // [ 1, 2, 3, 4, 5 ]

2. Use regular expressions

The array elements obtained by the following methods will be converted into strings, which is not recommended;

const result1 = JSON.stringify(arr).replace(/\[|\]/g, '').split(',')
console.log(result1) // [ '1', '2', '3', '4', '5' ] Array elements are converted to strings

Optimize the above methods;

const result2 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']')
console.log(result2) // [ 1, 2, 3, 4, 5 ]

3. Use reduce()+concat()

Use reduce to get the current value and the previous value of the array, determine whether the current value is an array, set the initial value to [], and then use concat to merge the arrays.

  • reduce() method: Executes a reducer function you provide for each element in the array (in ascending order), summarizing the results into a single return value.
  • concat() method: used to merge two or more arrays. This method does not mutate the existing array but returns a new array.
function flatten(arr) {
  return arr.reduce((pre, current) => {
    return pre.concat(Array.isArray(current) ? flatten(current) : current)
  }, [])
}
const result = flatten(arr)
console.log(result) // [ 1, 2, 3, 4, 5 ]

4. Use function recursion

Loop through the array, and recursively process if it contains array elements, and finally convert the array into a one-dimensional array.

const result = []
function exec(arr) {
  arr.forEach(item => {
    if (Array.isArray(item)) {
      exec(item)
    } else {
      result.push(item)
    }
  })
}
exec(arr)
console.log(result) // [ 1, 2, 3, 4, 5 ]

5. Use the spread operator + concat()

The new spread operator introduced in ES6 can reduce the dimension of an array (one dimension at a time), loop to determine whether it contains an array, and perform concat merging.

some() method: Tests whether there is at least one element in the array that passes the provided function test (it returns a Boolean value).

function flatten(arr) {
  while (arr.some(item => Array.isArray(item))) {
    arr = [].concat(...arr)
  }
  return arr
}
const result = flatten(arr)
console.log(result) // [ 1, 2, 3, 4, 5 ]

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • JS array deduplication details
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • In-depth study of JavaScript array deduplication problem
  • JavaScript array deduplication solution
  • JavaScript data flattening detailed explanation
  • JavaScript Interview: How to implement array flattening method
  • 5 JavaScript Ways to Flatten Arrays
  • Introduction to JavaScript array deduplication and flattening functions

<<:  Detailed explanation of how to quickly build a blog website using Docker

>>:  Detailed explanation of the setting of background-image attribute in HTML

Recommend

Discuss the development trend of Baidu Encyclopedia UI

<br />The official version of Baidu Encyclop...

Network configuration of Host Only+NAT mode under VirtualBox

The network configuration of Host Only+NAT mode u...

Detailed explanation of MySQL startup options and system variables examples

Table of contents Boot Options Command Line Long ...

Coexistence of python2 and python3 under centos7 system

The first step is to check the version number and...

Vue implements star rating with decimal points

This article shares the specific code of Vue to i...

How to create scheduled tasks using crond tool in Linux

Preface Crond is a scheduled execution tool under...

Collection of 12 practical web online tools

1. Favicon.cc To create ico icon websites online,...

MySQL 8.0.12 Installation and Usage Tutorial

Recorded the installation and use tutorial of MyS...

What are the differences between sql and mysql

What is SQL? SQL is a language used to operate da...

How to convert Chinese into UTF-8 in HTML

In HTML, the Chinese phrase “學好好學” can be express...

jQuery implements accordion small case

This article shares the specific code of jQuery t...

Some conclusions on developing mobile websites

The mobile version of the website should at least...