Array flattening and de-duplication and sorting

The following array is known: var arr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]] ] ], 10];

Write a program to flatten the array and remove the repeated part of the data, and finally get an ascending and non-repeating array

Array flattening is to convert a multi-level nested array to only one level

  • Recursive implementation:

    • function flatten(arr){
              
              
          let res = [];
          for(let i = 0; i < arr.length; i++){
              
              
              if(Array.isArray(arr[i])){
              
              
                  res.push(...flatten(arr[i]));
              }else{
              
              
                  res.push(arr[i])
              }
          }
          return res;
      }
      
  • reduce achieve

    • function flatten(arr) {
              
              
        return arr.reduce((res,cur) => {
              
              
          return res.concat(Array.isArray(cur)? flatten(cur) : cur)
        },[])
      }
      
  • Use the ...spread operator ...to expand a level of nesting, such as: …[1,2,[3,4]] The result is [1,2,3,4], but …[1,[2,[3,4 ]]] The result is [1,2,[3,4]]

    • function(arr){
              
              
          while(arr.some(item => Array.isArray(item)){
              
              
          	arr = [].concat(...arr)      
          })
      }
      
  • ES6's flat(), arr.flat(depth): The parameter depth specifies the number of layers to be flattened, the default is 1, and the parameter can be set to Infinity until it is flattened to one layer.

    • var arr = arr.flat(Infinity)
      

Implement deduplication and sorting after flattening

let res = Array.from(new Set(arr.flat(Infinity))).sort((a,b) => a-b)

Guess you like

Origin blog.csdn.net/Pinoochio/article/details/113513318