current position:Home>Implementation of array flattening
Implementation of array flattening
2021-08-27 03:18:33 【Yangyan】
Flattening of arrays
1. What is array flattening
The so-called flattening of arrays , It refers to converting an array with multiple nested layers into an array without nesting . for example : take [1, [2, 3], [4, [5, [6]]]]
Convert into [1, 2, 3, 4, 5, 6]
const arr = [1, [2, 3], [4, [5, [6]]]]
arr.flat(3) //=> [1, 2, 3, 4, 5, 6]
Copy code
2. Implementation of array flattening
1. Initially realized
Flatten the passed in array and return
(function() {
function flatten(res = []) {
const array = this
for (let i = 0, len = array.length; i < len; i ++) {
const val = array[i]
if (Array.isArray(val)) { // If it's an array , Flatten it
val.flatten(res)
} else { // If it's not an array , Then put the element directly into res that will do
res.push(val)
}
}
return res
}
Array.prototype.flatten = flatten
})()
const array = [1, 2, [3, [4, [5, 6, [7, 8]]]]]
array.flatten() //=> [1, 2, 3, 4, 5, 6, 7, 8]
Copy code
2. Further realization
It's easy to see , and JS
Medium flat
comparison , The initial implementation was less depth
Parameters ( Anti nesting depth ), Add here
(function() {
function flatten(depth = 1, res = []) {
const array = this
for (let i = 0, len = array.length; i < len; i ++) {
const val = array[i]
if (Array.isArray(val) && depth > 0) {
// If val It's an array , And it needs to be flattened
val.flatten(depth - 1, res)
} else {
res.push(val)
}
}
return res
}
Array.prototype.flatten = flatten
})()
const array = [1, 2, [3, [4, [5, 6, [7, 8]]]]]
array.flatten(3) //=> [1, 2, 3, 4, 5, 6, [7, 8]]
Copy code
Although remove res
The parameter is closer to flat
function , But to prevent every execution flatten
Functions need to create a res
Array , Each time you accept a recursive return value, you also need to expand it , It's a waste of time , It's a waste of space , So... Is not removed res
Parameters . As shown below :
(function() {
function flatten(depth = 1) {
const array = this
const res = []
for (let i = 0, len = array.length; i < len; i ++) {
const val = array[i]
if (Array.isArray(val) && depth > 0) {
res.push(...val.flatten(depth - 1))
} else {
res.push(val)
}
}
return res
}
Array.prototype.flatten = flatten
})()
Copy code
3. Final realization
When flatten
Call to depth === 1
when , Directly use the extension operator to add to res
The array can be , Improve program efficiency
otherwise , You don't just need another layer of recursion , And every time you traverse an element, you have to go through multiple judgments
(function() {
function flatten(depth = 1, res = []) {
const array = this
for (let i = 0, len = array.length; i < len; i ++) {
const val = array[i]
if (Array.isArray(val) && depth > 0) {
if (depth === 1) {
res.push(...val)
} else {
val.flatten(depth - 1, res)
}
} else {
res.push(val)
}
}
return res
}
Array.prototype.flatten = flatten
})()
const array = [1, 2, [3, [4, [5, 6, [7, 8]]]]]
array.flatten(3) //=> [1, 2, 3, 4, 5, 6, [7, 8]]
Copy code
3. Other implementation directions of array flattening
1. utilize Array.prototype.reduce
Realization
(function() {
function flatten() {
const array = this
const res = array.reduce((prevVal, curVal) => {
return prevVal.concat(Array.isArray(curVal) ? curVal.flatten() : curVal)
}, [])
return res
}
Array.prototype.flatten = flatten
})()
Copy code
2. utilize Array.prototype.some
Realization
(function() {
function flatten() {
const array = this
const res = [...array]
while (res.some(item => Array.isArray(item))) {
res = [].concat(...res)
}
return res
}
Array.prototype.flatten = flatten
})()
Copy code
3. utilize Array.prototype.splice
Realization
(function() {
function flatten() {
const array = this
const res = [...array]
for (let i = 0; i < res.length; i ++) {
if (Array.isArray(res[i])) {
res.splice(i, 1, ...res[i])
i --
}
}
return res
}
Array.prototype.flatten = flatten
})()
Copy code
4. utilize stack
Realization
(function() {
function flatten() {
const array = this
const stk = [...array]
const res = []
while (stk.length) {
let topVal = stk.pop()
if (Array.isArray(topVal)) {
stk.push(...topVal)
} else {
res.push(topVal)
}
}
return res.reverse()
}
Array.prototype.flatten = flatten
})()
Copy code
copyright notice
author[Yangyan],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827031831026n.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich