0

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()

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.