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

Detailed explanation of 4 common data sources in Spark SQL

Generic load/write methods Manually specify optio...

Use the sed command to modify the kv configuration file in Linux

sed is a character stream editor under Unix, that...

Detailed explanation of software configuration using docker-compose in linux

Preface This article will share some docker-compo...

Detailed steps for Python script self-start and scheduled start under Linux

1. Python automatically runs at startup Suppose t...

Pure CSS to achieve candle melting (water droplets) sample code

Achieve results Implementation ideas The melting ...

How to implement variable expression selector in Vue

Table of contents Defining the HTML structure Inp...

Example of implementing element table row and column dragging

The element ui table does not have a built-in dra...

Simple implementation method of vue3 source code analysis

Table of contents Preface 🍹Preparation 🍲vue3 usag...

Summary of commonly used operators and functions in MySQL

Let’s build the data table first. use test; creat...

VMware15/16 Detailed steps to unlock VMware and install MacOS

VMware version: VMware-workstation-full-16 VMware...

How to Rename Multiple Files at Once in Linux

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

Tips for optimizing MySQL SQL statements

When faced with a SQL statement that is not optim...

Implementation of mysql decimal data type conversion

Recently, I encountered a database with the follo...

Neon light effects implemented with pure CSS3

This is the effect to be achieved: You can see th...

Display ellipsis effect when table cell content exceeds (implementation code)

illustrate In front-end development, you often en...