user2167582
user2167582

Reputation: 6368

are there a javascript or lodash function that makes it easy to iterate through pairs or triples

so I want to fill in the every(#) here:

var arr = [1,2,3,4,5,6,7,8]

arr.every(2)(function(a,b) {
  return a + b;
})

// [3, 5, 7, 9, 11, 13, 15]

arr.every(3)(function(a,b,c) {
  return a + b + c;
})

// [6, 9, 12, 15, 18, 21]

Upvotes: 0

Views: 472

Answers (3)

sundar
sundar

Reputation: 408

There is no such method available in java script . you have to implement one by yourself.by extending array's prototype.

there is already a method in javascript named "every" which will be used to find whether all elements are satisfying some condition.

so use different name or caps or underscore to avoid overriding.

Edited as per your requirement

Array.prototype._every = function (n, callback) {

             if ( n > this.length ) 
                 return new Error("Invalid pair size"); 

             var everyEl = new Array(this.length - (n - 1)),result = []; 

             var original = this, temp = new Array(n);

             original.forEach(function (val, ind) {

                   if ( (ind + 1) >= n ) {
                      result[ ind-n ] = callback.apply(this, original.slice(n - ind - 1, ind, n));    
                   } 

             });

            return result;

   }

you should call this method like this

var arr = [10,20,30,40];

arr._every(2, function(a, b){
     return a+b;
});

Upvotes: 0

George Houpis
George Houpis

Reputation: 1729

Use the reduce function:

arr.reduce(function(p,v,i,a) { if( i + 1 < a.length ) p.push( a[i] + a[i + 1] ); return p; },[]);
arr.reduce(function(p,v,i,a) { if( i + 2 < a.length ) p.push( a[i] + a[i + 1] + a[i + 2]); return p; },[]);

I would not override the array prototype lightly. If you want a function that does every:

every = function(a,n,c) { return a.reduce(function(p,v,i,a) { if( i + n - 1 < a.length ) p.push( c.apply( this, a.slice( i, i + n ) ) ); return p; }, [] ); };

every(arr,2,function(a,b){return a+b;});
every(arr,3,function(a,b,c){return a+b+c;});

Upvotes: 1

user4454229
user4454229

Reputation:

Well, technically you can just assign the jump variable in the interval you want: for (var i = 0; i < arr.length; i += 2). You can bump that 2 to anything you want.

Upvotes: 0

Related Questions