Write a program to realize the flattening of the array, to repeat, and finally get an ascending and non-repeating array

Note:

  1. Flat: arr. Flat (Infinity)
  2. […new Set(arr)] array. from(new Set(arr))
  3. 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

  1. 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

  1. 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

  1. Arr.tostring () // Converts multidimensional arrays directly to strings
  2. Arr.tostring ().split(‘, ‘) // Separate with commas
  3. 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

  1. Json.stringify (arr) (Converts a JSON-formatted object into a JSON-formatted string)

Note:

  1. Convert a JSON-formatted object to a JSON-formatted string with json.stringfy (arr)
  2. Through the replace () method to convert “[]” to empty (replace (/ ([|])/g, ‘ ‘))
  3. Split the string into an array with a comma via split(‘, ‘)
  4. Converts each item traversal in the array to a Number using the map() and Number() methods
  5. 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

  1. 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

  1. 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

\