How to parse the deduplication and flattening function of JavaScript array
This article will explain in detail how to parse the JavaScript array de-duplication and flattening function, the content of the article is of high quality, so the editor will share it for you to do a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
1. Array flattening (also called array dimensionality reduction)
The flat () method recursively traverses the array at a specified depth and merges all elements with the elements in the traversed subarray into a new array.
Const test = ["a", [b "," c "], [" d ", [e", [f "]," g "] / / flat flattens a layer of test.flat () / / [" a "," b "," c "," d ", [e", [f "]," g "] / / pass in an integer parameter by default An integer is the number of flattened layers test.flat (2) / / ["a", "b", "c", "d", "e", ["f"], "g"] / / Infinity keyword as a parameter, no matter how many layers are nested Will be converted to an one-dimensional array test.flat (Infinity) / / ["a", "b", "c", "d", "e", "f", "g"] / / input [... acc,... flattenDeep (cur)], []): [arr]} / / Test var test = ["a", ["b", "c"], ["d", ["e") ["f"]], "g"]] flattenDeep (test) / / ["a", "b", "c", "d", "e", "f", "g"]
Implement the flat function:
Function flat (arr, depth = 1) {return depth > 0? Arr.reduce ((acc, cur) = > {if (Array.isArray (cur)) {return [... acc,... flat (cur, depth-1)]} return [... acc, cur]}, []: arr} / / Test var test = ["a", ["b", "c"], ["d", ["e", ["f"]] "g"]] / / when no parameter is passed Default flattening one layer flat (test) / / ["a", "b", "c", "d", ["e", ["f"]], "g"] / / pass an integer parameter, the integer is the flattened number of layers flat (test, 2) / / ["a", "b", "c", "d", "e", ["f"], "g"] / / Infinity keyword as a parameter No matter how many layers are nested, it will be converted to an one-dimensional array flat (test, Infinity) / / ["a", "b", "c", "d", "e", "f", "g"] / / input [. New Set (arr)] / / Test var arr = [1, 2, 2, 3] unique (arr) / / method 2: reducefunction unique (arr) {return arr.sort (). Reduce ((acc, cur) = > {if (acc.length = 0 | | acc [acc.length-1]! = = cur) {acc.push (cur);} return acc}, [])}; / / Test var arr = [1, 2, 2, 3] unique (arr) / / [1,2,3] method 3: filterfunction unique (arr) {return arr.filter ((element, index, array) = > {return array.indexOf (element) = index})} / / Test var arr = [1,2,2,3] unique (arr) / / [1, 2, 3] so much for parsing the deduplication and flattening functions of the JavaScript array. I hope the above can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.