benhowdle89
benhowdle89

Reputation: 37464

Using JavaScript's Reduce to create an array from an array of objects

So the following code is what I'm trying to achieve:

var arr = [{
    name: 'foo',
    amount: 2
}, {
    name: 'foo',
    amount: 4
}, {
    name: 'foo',
    amount: 6
}, {
    name: 'foo',
    amount: 1
}, {
    name: 'foo',
    amount: 5
}, ];

var newArr = arr.reduce(function (a, b) {
    return a.push(b.amount);
}, []);
console.log(newArr); // which I'd expect to be [2, 4, 6, 1, 5]

But this errors: Uncaught TypeError: Object 1 has no method 'push'. I know I could do this with .forEach() but I'm wondering if it's possible with .reduce()

Upvotes: 0

Views: 62

Answers (2)

Schnodderbalken
Schnodderbalken

Reputation: 3467

You have an array of objects there. So of course the objects don't know the function push which can be only applied on arrays. Even if those were arrays it would not work because push returns the new length of the array. You should use map instead of reduce to achieve what you want to do.

Upvotes: 0

georg
georg

Reputation: 214959

You need map, not reduce:

amounts = arr.map(function(x) { return x.amount })

If you want reduce, it goes like this:

var newArr = arr.reduce(function (a, b) {
    a.push(b.amount);
    return a;
}, []);

The reduce callback is supposed to return the accumulator object.

Upvotes: 3

Related Questions