multiplyOddByTwo function using javascript

Viewed 90

I'm trying to get the odd numbers in the following array and then multiply by 2 using reduce method but it's giving me undefined error. Any help please.

const multiplyOddByTwo = (arr) => {
  return arr.reduce((acc, curr) => {
    if (curr % 2 === 0) {
      arr.push(curr);
    } else {
      arr.push(curr * 2)
    }
  }, [])
}

console.log(multiplyOddByTwo([1, 2, 3]));

2 Answers

Two things to point out:

  1. You have to make modifications to the second param in your reduce function. It is your initial value. The first param in the reduce callback(acc) is your cumulated value up till that particular iteration.
  2. You have to return your cumulated value in each iteration. (When in the final iteration, this will be your calculated answer. Here you aren't returning anything hence the undefined)

const multiplyOddByTwo = (arr) => {
  return arr.reduce((acc, curr) => {
    if (curr % 2 === 0) {
      acc.push(curr);
    } else {
      acc.push(curr * 2)
    }
    return acc;
  }, [])
}

console.log(multiplyOddByTwo([1, 2, 3])); // [2,2,6]

This multiplies odd index elements by 2.

Edit: That is not undefined error. That is just undefined being returned. Any function not returning anything returns undefined.

If you would like it to only return odd numbers multiplied by 2 and not return the even then use this:

const multiplyOddByTwo = (arr) => {
    const odd = arr.filter(num => num % 2 !== 0);
    return odd.map(i => i * 2);
}

console.log(multiplyOddByTwo([1, 2, 3]));

Otherwise if you would like it to return all numbers but multiply odd numbers by 2 then use this:

const multiplyOddByTwo = (arr) => {
    return arr.map(num => num % 2 === 0 ? num : num * 2);
}

console.log(multiplyOddByTwo([1, 2, 3]));

Related