azaria.dee
azaria.dee

Reputation: 83

How to return a new array only containing odd numbers

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].

Upvotes: 1

Views: 1151

Answers (4)

Piyush Rana
Piyush Rana

Reputation: 667

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

Upvotes: 1

Sreekumar R
Sreekumar R

Reputation: 599

> 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 ]

Upvotes: 1

Derek Wang
Derek Wang

Reputation: 10194

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]));

Upvotes: 1

Ahmad Suddle
Ahmad Suddle

Reputation: 190

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

Upvotes: 1

Related Questions