javascript map和reduce array list

时间:2017-08-30 19:21:20

标签: javascript

我有一个这种格式的数组列表

 data = [[1,2,3,4,5,6,7,8,9,10],
 [11,12,13,14,15,16,17,18,19,20],
 [21,22,23,24,25,26,27,28,29,30]]

我想要这种格式的输出

    [[11/1, 12/2,13/3,14/4,15/5,16/6,17/7,18/8,19/9,20/10],
     [21/11,22/12,23/13,24/14,25/15,26/16,27/17,28/18,29/19,30/20]]

我用过循环,这就是它的外观

const totalData = data.length;
for(var i =0 ; i < totalData ; i++){
  for(var j =0; j < data[i].length; j++){
    console.log(data[i+1][j]/data[i][j]);
  }
}

我想用javascript地图转换这个并减少?有什么可能吗? 谢谢

4 个答案:

答案 0 :(得分:2)

for循环不是不好的做法,它们只是不适合编程的功能风格。以下解决方案预先假定数组的长度相等:

const data = [
  [1,2,3,4,5,6,7,8,9,10],
  [11,12,13,14,15,16,17,18,19,20],
  [21,22,23,24,25,26,27,28,29,30]
];

const result = data.map((arr, index) => {
  const next = data[index + 1];
  if (!Array.isArray(next)) {
    return;
  }
  return arr.map((item, i) => next[i] / item);
}).filter(Boolean);

console.log(result);

我相信如果数组的长度不相等,你可以弄明白该做什么。

答案 1 :(得分:1)

You could use a single reduce and map the items for a new array.

RANKCOMPANYGROWTHREVENUEINDUSTRY 1Skillz50,058.92%$54.2mSoftware2EnviroSolar Power36,065.06%$37.4mEnergy
RANK|COMPANY|GROWTH|REVENUE|INDUSTRY
1|Skillz|50,058.92%|$54.2m|Software
2|EnviroSolar Power|36,065.06|$37.4m|Energy

答案 2 :(得分:0)

您需要为每项任务创建单独的函数:

/**
 * Combine 2 arrays
 * @param Array a 
 * @param Array b 
 */
function combineArrays(a, b) {

    var combined = [];

    for (var i = 0; i < a.length; i++)
        combined.push(a[i] / b[i]);

    return combined;
}

/**
 * Combine an group of arrays
 * @param Array group 
 */
function combineGroup(group) {
    var newGroup = [];
    for (var i = 0; i < group.length - 1; i++)
        newGroup.push(combineArrays(group[i], group[i + 1]));

    return newGroup;

}

第一个函数仅组合2个数组。 第二个函数组合了许多数组并返回你想要的数据。

答案 3 :(得分:0)

如果长度不相等,则忽略较长的尾部中的项目。

data = [
  [1,2,3,4,5,6,7,8,9,10],
  [11,12,13,14,15,16,17,18,19,20],
  [21,22,23,24,25,26,27,28,29,30]
];

result = data.reduce((acc,current,i)=>{
      var ret;
      if(data[i].length <= data[i-1].length)
        ret = data[i].map((item,j)=>(item / data[i-1][j]));
      else
        ret = data[i-1].map((item,j)=>(data[i][j] / item));
      if(i==1)
        return [ret]
      else
        return acc.concat([ret])
})
console.log(result)