2

As an exercise I'm trying to convert a map example to use reduce:

const numbers = [1, 2, 3, 4];

numbers.map(function(a,b) {
    return a+b;
});
// [1, 3, 5, 7]

my attempt for same example with reduce:

numbers.reduce(
  (sum, elem) => {
    sum.push(elem + elem); // how can one add the index of array to the number instead of doubling it?
    return sum;
  }, []);
// [2, 4, 6, 8], instead I want: [1, 3, 5, 7]

2 Answers 2

5

Your result with reduce. Pass the third parameter, which is the index

const numbers = [1, 2, 3, 4];


var arr = numbers.reduce(
  (sum, elem, index) => {
    sum.push(elem + index);
    return sum;
  }, []);

console.log(arr);

But

Your map function works as you want only by accidently :).

map function accepts as parameters not the 2 sibling items, but an item and it's index.

See here. If you change the pre-last item, you will get an other behaviour. In your logic the last item must be 11,if it accepts 2 sibling items, but not it is still 7, because it accepts the item and it's index.

Example with changed data.

1 -> 1 + 0 (index) = 1
2 -> 2 + 1 (index) = 3
3 -> 3 + 2 (index) = 5
4 -> 4 + 3 (index) = 7

const numbers = [1, 2, 7, 4];

var arr = numbers.map(function(a,b) {
    return a+b;
});

console.log(arr);

Output

1 -> 1 + 0 (index) = 1
2 -> 2 + 1 (index) = 3
7 -> 7 + 2 (index) = 9
4 -> 4 + 3 (index) = 7

reduce function accepts in it's basic form two parameters, the item of the array and the returned value from the previous iteration.

So I think you understood these functions not well.

You can read more in the Array#map() and Array#reduce()

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

1 Comment

hmm, I just wanted the same result of the map example with reduce. In your answer you elaborate the map example but didn't answer my question.
1

You could add the previous item with a check for truthyness and the actual item. Return the array with concatinated value.

var numbers = [1, 2, 3, 4],
    result = numbers.reduce((r, a, i, aa) => r.concat((aa[i - 1] || 0) + a), []);

console.log(result);

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.