阵列的总和阵列(矩阵)垂直高效/优雅 [英] Sum array of arrays (matrix) vertically efficiently/elegantly

查看:165
本文介绍了阵列的总和阵列(矩阵)垂直高效/优雅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,如果我有一个数组的数组重新presenting一个矩阵,说

In Javascript, if I have an array of arrays representing a matrix, say

x = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]
];

总结为横向是容易的,可以像

summing it "horizontally" is easy and can be done like

x.map(function(y){
    return y.reduce(function(a,b){
        return a+b;
    });
});

现在我想计算垂直总之,这是可以做到

Now I would like to compute the "vertical" sum, which can be done

x.reduce(function(a, b){
    return a.map(function(v,i){
        return v+b[i];
    });
});

但我不满意这个版本,我希望能有更好的东西,更优雅,更简单。也许一个简单的方法来事先转置矩阵?任何人吗?

But I am not happy with this version and I wish there were something nicer, more elegant and more straightforward. Maybe an easy way to transpose the matrix beforehand? anyone?

请注意,我问了一个类似的问题,前几天(<一个href=\"http://stackoverflow.com/questions/32019544/combining-two-arrays-of-same-size-and-returns-sum?noredirect=1#comment51941758_32019544\">link)但缺乏大局观。

Note that I asked a similar question a few days ago (link) but that lacked the bigger picture.

推荐答案

我认为你是不快乐的,有没有原生拉链的功能,因为这是你的减少地图基本上做的事情。你要么自己实现它,或者从如 Ramda 库导入,为了写优雅code是这样的:

I think you are unhappy that there is no native zip function, because that's what your reduce in the map is essentially doing. You'll either have to implement it yourself or import it from a library like Ramda, in order to write elegant code like this:

var verticalSum = x.map(R.zipWith(function(a,b){ return a+b; }));

如果你正在寻找一个有效的解决方案,也基本上不会比显式循环更好的办法。

If you are looking for an efficient solution, there's basically no better way than explicit loops.

这篇关于阵列的总和阵列(矩阵)垂直高效/优雅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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