amaity
amaity

Reputation: 267

How to reduce an array using lodash

I have the following array:

arr = [
    [
        [1, 2],
        [3, 4],
        [5, 6]
    ],
    [
        [7, 8],
        [9, 10],
        [11, 12]
    ],
    [
        [13, 14],
        [15, 16],
        [17, 18]
    ]
];

How can I reduce it the following using lodash:

[[9,12],[27,30],[45,48]]

I am a complete noob. I don't know what to do beyond this:

_.forEach(arr, function (n) {
    console.log(JSON.stringify(_.zip(n)));
});

Some hints please.

Upvotes: 1

Views: 946

Answers (2)

Amit
Amit

Reputation: 46323

Similar to your attempt, combination of map, zipWith & add with some partialRight help :-)

var zipAdd = _.partialRight(_.zipWith, _.add)
var result = _.map(arr, function(a) {
  return zipAdd.apply(null, a)
});

Working snippet

var arr = [
  [
    [1, 2],
    [3, 4],
    [5, 6]
  ],
  [
    [7, 8],
    [9, 10],
    [11, 12]
  ],
  [
    [13, 14],
    [15, 16],
    [17, 18]
  ]
];

var zipAdd = _.partialRight(_.zipWith, _.add)
var result = _.map(arr, function(a) {
  return zipAdd.apply(null, a)
});

alert(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>

Upvotes: 0

robertklep
robertklep

Reputation: 203359

Using a mix of lodash (_.unzip() and _.sum()) and Array methods (Array#map()):

var result = arr.map(function(a) {
  return _.unzip(a).map(_.sum);
});

Upvotes: 3

Related Questions