Namespace: reduce

async.reduce

Source:

Examples

// array
var order = [];
var collection = [1, 3, 2, 4];
var iterator = function(result, num, done) {
  setTimeout(function() {
    order.push(num);
    done(null, result + num);
  }, num * 10);
};
async.reduce(collection, 0, iterator, function(err, res) {
  console.log(res); // 10
  console.log(order); // [1, 3, 2, 4]
});
// array with index
var order = [];
var collection = [1, 3, 2, 4];
var iterator = function(result, num, index, done) {
  setTimeout(function() {
    order.push([num, index]);
    done(null, result + num);
  }, num * 10);
};
async.reduce(collection, '', iterator, function(err, res) {
  console.log(res); // '1324'
  console.log(order); // [[1, 0], [3, 1], [2, 2], [4, 3]]
});
// object
var order = [];
var object = { a: 1, b: 3, c: 2, d: 4 };
var iterator = function(result, num, done) {
  setTimeout(function() {
    order.push(num);
    done(null, result + num);
  }, num * 10);
};
async.reduce(collection, '', iterator, function(err, res) {
  console.log(res); // '1324'
  console.log(order); // [1, 3, 2, 4]
});
// object with key
var order = [];
var object = { a: 1, b: 3, c: 2, d: 4 };
var iterator = function(result, num, key, done) {
  setTimeout(function() {
    order.push([num, key]);
    done(null, result + num);
  }, num * 10);
};
async.reduce(collection, 0, iterator, function(err, res) {
  console.log(res); // 10
  console.log(order); // [[1, 'a'], [3, 'b'], [2, 'b'], [4, 'd']]
});