当前位置:网站首页>[JS] array dimensionality reduction

[JS] array dimensionality reduction

2022-07-05 10:19:00 A meteor unwilling to fall

List of articles

In the project , We often have to deal with data structures that are more replicated , And there is no ready-made method , At this time, we need to use it manually js Native to encapsulate one , Here is the method of reducing multidimensional array to one level structure , For example, three-dimensional array to two-dimensional array 、 Two dimensional array to one dimensional array .

  • data structure :
//  Three dimensional array 
[
    [
        [
            8,
            680
        ]
    ],
    [
        [
            6,
            681
        ]
    ]
]
//  Two dimensional array 
[
    [
        8,
        680
    ],
    [
        6,
        681
    ]
]
  • Method 1:reduce + concat
const arr3 = [ [ [ 8, 680 ] ],  [ [ 6, 681 ] ] ];
const arr2 = [ [ 8, 680 ],  [ 6, 681 ] ];
function arr3ToArr2(arr){
    
	return arr.reduce((acc, val) => acc.concat(val), []);
}
console.log(arr3ToArr2(arr3))	// [ [ 8, 680 ], [ 6, 681 ] ]
  • Method 2:... + concat
const arr3 = [ [ [ 8, 680 ] ],  [ [ 6, 681 ] ] ];
const arr2 = [ [ 8, 680 ],  [ 6, 681 ] ];
function arr3ToArr2(arr){
    
	return [].concat(...arr)
}
console.log(arr3ToArr2(arr3))	// [ [ 8, 680 ], [ 6, 681 ] ]
原网站

版权声明
本文为[A meteor unwilling to fall]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050946365333.html