Write a program to realize the flattening of the array, to repeat, and finally get an ascending and non-repeating array
Note:
- Flat: arr. Flat (Infinity)
- […new Set(arr)] array. from(new Set(arr))
- Sorting: sort ()
let arr = [1, 2, 3, 45, 58, [154, 25, 14, 14, [4587, 45, 125, [145, 20, 145, 23, [12, 10]]]]]
Copy the code
- Use array.prototype. flat(Infinity) provided in ES6
let arr = [1, 2, 3, 45, 58, [154, 25, 14, 14, [4587, 45, 125, [145, 20, 145, 23, [12, 10]]]]]
arr = Array.from(new Set(arr.flat(Infinity))).sort((a, b) => a - b)
console.log(arr)
Copy the code
- Using the toString () method, the array is flattened and then reordered
Note: No matter how many levels you pass through toString(), you end up with a comma-separated string without brackets and levels
- Arr.tostring () // Converts multidimensional arrays directly to strings
- Arr.tostring ().split(‘, ‘) // Separate with commas
- Arr.map (item=>{return Number(item)}) // Convert a string to a Number using the map method
let arr = [1, 2, 3, 45, 58, [154, 25, 14, 14, [4587, 45, 125, [145, 20, 145, 23, [12, 10]]]]]
arr = arr.toString().split(',').map(item => { return Number(item) })
Copy the code
- Json.stringify (arr) (Converts a JSON-formatted object into a JSON-formatted string)
Note:
- Convert a JSON-formatted object to a JSON-formatted string with json.stringfy (arr)
- Through the replace () method to convert “[]” to empty (replace (/ ([|])/g, ‘ ‘))
- Split the string into an array with a comma via split(‘, ‘)
- Converts each item traversal in the array to a Number using the map() and Number() methods
- Sort by the sort () method
let arr = [1, 2, 3, 45, 58, [154, 25, 14, 14, [4587, 45, 125, [145, 20, 145, 23, [12, 10]]]]]
arr = JSON.stringify(arr).replace(/([|])/g, '').split(',').map(item => { return Number(item) }).sort((a, b) => { return a - b })
Copy the code
- Use a loop some()+ While() +concat()
Note: The some() method returns true or false to check whether an item in the array matches the rule provided in the function
Some returns Boolean; Some returns Boolean; Some returns Boolean; Some returns Boolean
let arr = [1, 2, 3, 45, 58, [154, 25, 14, 14, [4587, 45, 125, [145, 20, 145, 23, [12, 10]]]]] while (arr.some(item => { return Array.isArray(item) })) { arr = [].concat(... arr) }Copy the code
- recursive
let arr = [1, 2, 3, 45, 58, [154, 25, 14, 14, [4587, 45, 125, [145, 20, 145, 23, [12, 10]]]]] ~function () { function myFlat() { let result = [], _this = this; Let fn = (arr) => {for (let item of arr) {if (array.isarray (item)) {fn(item); continue; } result.push(item) } } fn(_this); return result; } Array.prototype.myFlat = myFlat }(); arr = arr.myFlat();Copy the code
\