dqde43215
2017-04-08 07:22
浏览 30

在JS中转换数组

Help, please.

How is it possible in JS to transform these arrays:

$ar1 = array('Shop 1', 15, 25, 30);
$ar2 = array('Shop 2', 25, 45, 50);
$ar3 = array('Month', 1, 2, 3);

to this:

$values = array(
   array('Month', 'Shop 1', 'Shop 2'),
   array('1', 15, 25),
   array('2', 25, 45),
   array('3', 30, 50),
);

in PHP I can do it as follow:

$result = array_map(function($a,$b,$c){ return [$a,$b,$c]; }, $ar3,$ar1,$ar2);

or like that:

function flip($arr) {
$result = array();
foreach ($arr as $index => $list) {
    foreach ($list as $key => $value) {
        $result[$key][$index] = $value;
    }
}
return $result;
}

$values = flip([$ar3, $ar1, $ar2]);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doupao6011 2017-04-08 07:45
    已采纳

    You can use Array.prototype.map in Javascript. It passes the array index as an argument to the callback, which you can then use to access the other two arrays.

    var arr1 = ['Shop 1', 15, 25, 30];
    var arr2 = ['Shop 2', 25, 45, 50];
    var arr3 = ['Month', 1, 2, 3];
    
    var result = arr3.map(function(element, index) {
      return [element, arr1[index], arr2[index]];
    });
    
    console.log(result);

    </div>
    
    点赞 打赏 评论
  • dongwen4630 2017-04-08 07:30

    You could try something like this:

    var arr1 = ['Shop 1', 15, 25, 30];
    var arr2 = ['Shop 2', 25, 45, 50];
    var arr3 = ['Month', 1, 2, 3];
    
    var res = [];
    Object.keys(arr3)
          .forEach(function(key){
              res.push([arr3[key].toString(), arr1[key], arr2[key]]); 
    });
    
    console.log(res);

    </div>
    
    点赞 打赏 评论
  • dongxia2068 2017-04-08 07:30

    With proper arrays, you could transform the single arrays with a nested loop for the result.

    var array1 = ['Shop 1', 15, 25, 30],
        array2 = ['Shop 2', 25, 45, 50],
        array3 = ['Month', 1, 2, 3],
        result = [array3, array1, array2].reduce(function (r, a, i) {
            a.forEach(function (b, j) {
                r[j] = r[j] || [];
                r[j][i] = b;
            });
            return r;
        }, []);
    
    console.log(result)
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    </div>
    
    点赞 打赏 评论

相关推荐 更多相似问题