1

I have an array and I want to double each odd number as well as return a new array with the newly doubled numbers. For some reason, the values won't double; here is my code.

function doubleOddNumbers(arr) {
  return arr.filter(function(value) {
    if(value%2 !== 0) {
      return value * 2
    }
  })
}

When I look at my results in the console I continue to get the same odd numbers instead of them being doubled e.g. [1,2,3,4] will return [1,3] instead of [2, 6].

2
  • 1
    Filter is used to keep and remove items, not to transform/map items. You first need to filter your array to keep the numbers which are odd, and then use .map() to transform/map those numbers. You should return true from the filter method when you want to keep an item, and false when you want to remove the item. Commented Oct 3, 2020 at 5:32
  • 1
    Ah, I see! Thank you. Commented Oct 3, 2020 at 5:34

4 Answers 4

1

It can work this way

function doubleOddNumbers(arr) {
  let newArr = [];
  arr.forEach(function(value) {
    if (value % 2 !== 0) {
      newArr.push(value * 2);
    }
  });
  return newArr;
}

console.log(doubleOddNumbers([1, 2, 3, 4, 5, 6, 7, 8]));

<!-- begin snippet: js hide: false console: true babel: false -->

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

Comments

1

You can simply do it using Array.reduce.

function doubleOddNumbers(input) {
  return input.reduce((acc, cur) => {
    if (cur % 2 !== 0) {
      acc.push(cur * 2);
    }
    return acc;
  }, []);
}

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

1 Comment

I think OP wants the output to be [2, 6], I could be wrong though
1
> var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
undefined
> var x = arr.filter( ele => (ele % 2 != 0) ).map (ele => ele * 2)
undefined
> x
[ 2, 6, 10, 14, 18 ]

Comments

1

First of all, filter method's return statement always of boolean type. It should never be used assuming that it would return something. If you wanna return doubled odd values from array, do something like this -

arr.filter((value) => value % 2 !== 0).map((value) => value * 2);

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.