-3

In an array, it prints out all odd numbers to even numbers, not changing even numbers. For example, [1, 2, 3, 4] => [2, 2, 6, 4]

var result = '';
var i = 0;

if(array[i]%2 === 1) {        
   result = array[i]*2;
} 

This code prints out only odd number, excluding even numbers in an array.

For example, [1, 2, 3] => [2]

Jaydeep
  • 1,686
  • 1
  • 16
  • 29
Daye Kang
  • 39
  • 4

6 Answers6

0

In the loop, check if the item is odd (% returns something other than 0). If it's odd push it's double, if not push the original number:

var array = [1, 2, 3, 4]

var result = []

for(var i = 0; i < array.length; i++) {
  result.push(array[i] % 2 ? array[i] * 2 : array[i])
}

console.log(result)

You can also use Array.map():

const array = [1, 2, 3, 4]

const result = array.map(n => n * (n % 2 + 1))

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Based on the given example:

[1, 2, 3, 4] => [2, 2, 6, 4]

I take it that every odd number has to be doubled. Based on that assumption, here is the code:

for (let i = 0; i < array.length; i++)
  if (array[i] % 2 !== 0)
    array[i] *= 2;

console.log(array);
Almog Gabay
  • 135
  • 7
0

try this:

var arr = [1, 2, 3, 4]

for (var i = 0; i < arr.length; i++) {
  if(arr[i]%2 != 0) {
    arr[i] = arr[i]*2;
  }
}

console.log(arr);
sdn404
  • 614
  • 5
  • 7
0

You need to push even numbers as well.

var array = [1, 2, 3, 4],
    result = [],
    i = 0;

for (i = 0; i < array.length; i++) {
    if (array[i] % 2 === 1) {
        result.push(array[i] * 2);
    } else {
        result.push(array[i]);
    }
}

console.log(result);

A shorter approach

var array = [1, 2, 3, 4],
    result = array.map(v => v % 2 ? 2 * v : v);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

you can use bitwise & also to check even or odd, lil faster if you have large arrays.

let out =  [1, 2, 3, 4].map(e => e & 1 ? e * 2 : e);
console.log(out)
AZ_
  • 3,094
  • 1
  • 9
  • 19
-1

var array = [1, 2, 3, 4]
var result = [];
  var i = 0;

for (var j = 0; j < array.length; j++) {
 if(array[j]%2 === 1) {

    result.push(array[j]*2);
  }  else {
result.push(array[j])
}
}
 
console.log(result)
Soumya Gangamwar
  • 954
  • 4
  • 16
  • 44