【问题标题】:JS: writing a function that has an input of a multidimensional arrayJS:编写一个具有多维数组输入的函数
【发布时间】:2018-11-08 18:21:29
【问题描述】:

我想输入一个数组数组,然后将它们分开。因此,例如,我有一个位置数组,例如多个纬度和经度坐标。 但我想编写一个循环,然后将获取该数组数组并为所有纬度坐标和所有经度坐标生成和数组。

例如,如果我有

输入 = [[45,45],[35,75][85,90]] 它会将 2 个数组作为我的输出 [45,35,85] 和 [45,75,90]

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以转置数组并将latlong 作为单个数组。

var input = [[45, 45], [35, 75], [85, 90]],
    [lat, long] = input.reduce((r, a) => a.map((v, i) => (r[i] || []).concat(v)), []);
    
console.log(lat);
console.log(long);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    试试这个,遍历每个坐标,并将每个坐标的第一个值放入名为first 的数组中,将每个坐标的第二个值放入名为second 的数组中。..

    var input = [[45,45],[35,75],[85,90]];
    
    function splitValues(coordinates) {
        var first = [];
        var second = [];
        for (var i = 0; i < coordinates.length; i++) {
        first.push(coordinates[i][0]);
        second.push(coordinates[i][1]);
      }
    }
    
    splitValues(input);
    

    【讨论】:

      【解决方案3】:

      这将有助于假设您在输入中始终有一个 2 值数组并且您只需要 2 个结果

      const array = [[45,45],[35,75],[85,90]]
      let first = []
      let second = []
      array.forEach((item)=>{
          first.push(item[0])
        second.push(item[1])
      })
      console.log(first)
      console.log(second)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-05
        • 1970-01-01
        • 2019-11-26
        • 2015-09-14
        • 2020-08-25
        相关资源
        最近更新 更多