Google 电子表格脚本 - 如何转置/旋转多维数组? [英] Google Spreadsheet Script - How to Transpose / Rotate Multi-dimensional Array?

查看:21
本文介绍了Google 电子表格脚本 - 如何转置/旋转多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数接受任何数组并将其转置,以便行变为列,列变为行.

I'm trying to create a function that takes in any array and transpose it so that rows turns to columns and columns to rows.

不确定我做错了什么或遗漏了什么,但在数组通过后不断收到此消息....

Not sure what I've done wrong or missing but keep getting this message once the array is pass through....

类型错误:无法将未定义的属性0.0"设置为xxxxxx".

TypeError: Cannot set property "0.0" of undefined to "xxxxxx".

错误在线

result[row][col] = array[col][row];//旋转

result[row][col] = array[col][row]; // Rotate

任何指针将不胜感激.

function transposeArray(array){
        var result = [];
        for(var row = 0; row < array.length; row++){ // Loop over rows
          for(var col = 0; col < array[row].length; col++){ // Loop over columns
            result[row][col] = array[col][row]; // Rotate
          }
        }
        return result;
    }

推荐答案

我个人最喜欢的是这个要点:

function transpose(a)
{
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}

这篇关于Google 电子表格脚本 - 如何转置/旋转多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆