Can I combine successive Sugar.js calls to Array.map?

434 Views Asked by At

For example, if my array is multi-dimensional:

var myArray = [
    {
        key1: {
            key2: 1,
            ...
        },
        ...
    },
    {
        key1: {
            key2: 2,
            ...
        },
        ...
    }
];

myArray.map('key1').sum('key2');
= 3

This could also be

myArray.map('key1').map('key2').sum();

but is there a way to combine them into one call to map?

1

There are 1 best solutions below

1
Raine Revere On BEST ANSWER

When map takes a string it is effectively a shortcut for pluck.

As described in the Sugar documentation, map can more traditionally take a function as well:

map( map , scope )

Maps the array to another array containing the values that are the result of calling map on each element. scope is the this object. In addition to providing this method for browsers that don't support it natively, this enhanced method also directly accepts a string, which is a shortcut for a function that gets that property (or invokes a function) on each element.

Returns: Array

Therefore:

myArray.map(function(x) { return x.key1.key2; }).sum()