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

HTML head tag meta to achieve refresh redirection

Copy code The code is as follows: <html> &l...

Upgrading Windows Server 2008R2 File Server to Windows Server 2016

The user organization has two Windows Server 2008...

React Native startup process detailed analysis

Introduction: This article takes the sample proje...

Detailed explanation of Linux host name modification command

Linux change hostname command 1. If you only need...

Beginners learn some HTML tags (2)

Related article: Beginners learn some HTML tags (1...

XHTML tags have a closing tag

<br />Original link: http://www.dudo.org/art...

How to implement page screenshot function in JS

"Page screenshot" is a requirement ofte...

CSS3 Bezier Curve Example: Creating Link Hover Animation Effects

We will use CSS3 animated transitions to create a...

Use of Vue filters and custom instructions

Table of contents Filters 01.What is 02. How to d...

Eight implementation solutions for cross-domain js front-end

Table of contents 1. jsonp cross-domain 2. docume...

Linux traceroute command usage detailed explanation

Traceroute allows us to know the path that inform...

How to move a red rectangle with the mouse in Linux character terminal

Everything is a file! UNIX has already said it. E...

MySQL 5.7.17 and workbench installation and configuration graphic tutorial

This article shares the installation and configur...

JavaScript countdown to close ads

Using Javascript to implement countdown to close ...