SoFunction
Updated on 2025-03-03

Detailed explanation of several methods of dimensionality reduction of JS arrays

Dimension reduction of two-dimensional arrays

Dimension reduction using array instance methods concat and ES6 extension operator

let arr=[1,2,[3,4],5];
let arr1=[].concat(...arr);
//First use the extension operator to break up the outermost array. Concat has the function of breaking and glueing the array(arr1);
// [1, 2, 3, 4, 5]

//Compare writing method of using apply to break up data before ES6var arr2=[1,2,[3,4],5];
var arr3=[].([],arr2);
(arr3);
// [1, 2, 3, 4, 5]

Multidimensional array dimension reduction

Recursive dimension reduction

// Several ways to use array functions to reduce the dimension recursively//some&concat
//Use some to check whether the array contains an array and call it to reduce the dimensions yourselffunction fun(arr){
  arr=[].concat(...arr); 
  // Check whether the array after dimensionality reduction still contains subarrays  let hasArray=(function(elem){
      return (elem);
  })
  if(hasArray){ //If subarrays are included      arr=fun(arr);//You can only reduce the dimension once again until the check does not contain subarrays anymore  }
    return arr;
};

//forEach&instanceof
//Judge each element of the array to see if it is the array that continues to call itself, and does not put it into an empty array prepared in advancefunction fun2(arr){
  let ret = [];
  let toArr = function(arr){
    (function(item){
      item instanceof Array ? toArr(item) : (item);
    });
  }
  toArr(arr);
  return ret;
}

//reduce&concat
//Finally prepare an empty array to see if each item passed into the array is an array. Then call it again. If you use concat to summarize it into the empty array.function fun3(sarr){
    return ((pre,val)=>{
        return (val) ? (fun3(val)): (val)
    },[])
}

()

ES10 has added() to break up nested arrays and turn them into one-dimensional arrays. This method returns a new array with no impact on the original data.

var arr1 = [1, 2, [3, 4]];
(); 
// [1, 2, 3, 4]
 
var arr2 = [1, 2, [3, 4, [5, 6]]];
();
// [1, 2, 3, 4, [5, 6]]
 
var arr3 = [1, 2, [3, 4, [5, 6]]];
(2);
// [1, 2, 3, 4, 5, 6]
 
//Use Infinity as depth to expand nested arrays of any depth(Infinity); 
// [1, 2, 3, 4, 5, 6]

This is the end of this article about several methods of dimensionality reduction of JS arrays. For more related content on dimensionality reduction of JS arrays, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!