Convert two-dimensional array to ordinary array

When dealing with multiple array combinations, it may often be spliced ​​into an array. Today we will talk about the transformation of arrays

Two-dimensional (or even above) variable one-dimensional array

I often use the third apply method

1. Use the combination of reduce and concat of es5

var list = [
  [111,222,3333,444],
  [555,666,777],
  [888],
  [999,1213]
]
var lists = list.reduce((a,b) => a.concat(b))
console.log(lists)

insert image description here
2. Use ES6's flat processing

var list = [
  [111,222,3333,444],
  [555,666,777],
  [888],
  [999,1213]
]
var lists = list.flat()
console.log(lists)

insert image description here
3. Realize with apply

var list = [
  [111,222,3333,444],
  [555,666,777],
  [888],
  [999,1213]
]
var lists = [].concat.apply([],list)
console.log(lists)

insert image description here
4. Realize with call

var list = [
  [111,222,3333,444],
  [555,666,777],
  [888],
  [999,1213]
]
var lists = [].concat.call([],...list)
console.log(lists)

insert image description here
5. Use recursion to convert multidimensional arrays into one-dimensional arrays

var list = [
	[111,222,3333,444],
	[ 555, 666, 777, [123] ],
	[ 888 ], 
	[ 999, 1212 ]
]
function flatten(arr) {
	return [].concat(...arr.map(x=>Array.isArray(x) ? flatten(x) : x))
}
var lists = flatten(list)
console.log(lists)

insert image description here
6. Transformation for simple multidimensional arrays

var list = [
  [111,222,3333,444],
  [555,666,777,[123]],
  [888],
  [999,1212]
]
var lists = (list + '').split(',')
console.log(lists.map(Number))

insert image description here
// let oneArr = values?.map((el) => {
// return el.getData.map((item) => {
// return {
// reportId: item.id,
// reportQty: item.editReportQty
// };
// });
// });
// var params = [].concat.apply([], oneArr);
// console.log(params);

Guess you like

Origin blog.csdn.net/lzfengquan/article/details/127731577