Javascript matrix addition of an arbitrary number of arrays' values, without using array.map()

I'm trying to build a helper function for my AngularJS app (but the solution doesn't have to use angular.forEach). The function should take an arbitrary number of arrays with same length and add the values together to form an new array, e.g.:

a = [1, 2, 3];
b = [4, 5, 6];
result = [5, 7, 9];

I'm trying to not use array.map() or sylvesterjs for IE8 compatibility. I'm stuck on looping through arguments as javascript doesn't seem to like nesting functions within a for loop. Code so far:

function arrayAdd () {
  // make sure all args have same length
  var totalLen = 0;
  angular.forEach(arguments, function (arg) {
    totalLen += arg.length;
  });
  var avgLen = totalLen / arguments.length;

  if (avgLen === arguments[0].length) {
    var arrNew = mkArray(0, arguments[0].length);
    // helper function to make an empty array, not shown here

    // need to refactor below with loop for unlimited # of args
    angular.forEach(arguments, function (arg, i) {
      arrNew[0] += arg[0];
    });
    angular.forEach(arguments, function (arg, i) {
      arrNew[1] += arg[1];
    });

    return arrNew;
  } else {
    throw 'arrayAdd expects args with equal length';
  }
}

Thanks!

Answers


No need for map, you only need to keep track of the arrays as you total them.

(This does not check that the arrays have the same length-)

  function sumArrayElements(){
        var arrays= arguments, results= [], 
        count= arrays[0].length, L= arrays.length, 
        sum, next= 0, i;
        while(next<count){
            sum= 0, i= 0;
            while(i<L){
                sum+= Number(arrays[i++][next]);
            }
            results[next++]= sum;
        }
        return results;
    }

var a= [1, 2, 3], b= [4, 5, 6], c= [1, 2, 3];
sumArrayElements(a, b, c)
/* returned value:(Array)
6, 9, 12
*/

Need Your Help

How could a cms application split content over multiple pages?

php ruby-on-rails content-management-system server-side

I have an idea for a website that involves content being split over multiple pages. Similar to this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.