JavaScript converts multiple arrays into two-dimensional arrays (echarts multidimensional array conversion, js converts multiple arrays into two-dimensional arrays)

Brief description: When we write echarts, the data is usually presented in the form of an array. However, sometimes we need to combine multiple arrays into a two-dimensional array for easier operation and display. Here we share how to Multiple arrays are converted into two-dimensional arrays.

 

Code conversion example, it is actually very simple

1. The first type

  const arr = [1, 2, 3, 4];
  const arr2 = [4, 3, 2, 1];

  const res = [arr, arr2];
  console.log(res);

 output

 

944d6515f726428eb69ae238b1c5c796.png

As you can see, just write the two arrays in the same array and assign them to the new array;

 

Two, the second

  const arr = [1, 2, 3, 4];
  const arr2 = [4, 3, 2, 1];

  const res2 = [arr].concat([arr2])
  console.log(res2);

 output

8309693bd2c54f9bb5590d5c20304d8f.png

 It can be seen that when using the concat method to splice the array, it can also be directly nested on the array with another layer of array, and the effect is the same as above;

 

By the way, how to convert a multidimensional array into a one-dimensional array?

  const arr3 = [1,[2,3],[4,[5,[6]],7]];
  const res3 = arr3.flat(Infinity)
  这里的Infinity是flat方法默认参数,默认转换为一维数组
  console.log(res3);

 output

b4387b6f7f364937b5e220b7b3f0a236.png It can be seen that using the default parameter Infinity of the flat method directly converts the multidimensional array into a one-dimensional array;

 other situations

const arr3 = [1,[2,3],[4,[5,[6]],7]];

1、flat不传参数时,默认去除一层数组嵌套
console.log(arr3.flat());
//控制台输出 [1,2,3,4,[5,[6]],7];

2、flat传入一个整数参数时,即拉平的层数
console.log(arr3.flat(2));
//控制台输出 [1,2,3,4,5,[6],7];

3、flat传入小于等于0的整数时,将返回原数组
console.log(arr3.flat(0));
//控制台输出 [1,[2,3],[4,[5,[6]],7]]
console.log(arr3.flat(-1));
//控制台输出 [1,[2,3],[4,[5,[6]],7]]

 

 

Guess you like

Origin blog.csdn.net/weixin_65793170/article/details/129989998