Skip to content Skip to sidebar Skip to footer

Applying Conditions To An Array

I have a problem applying to return an array after applying a condition. Here it is, With a given array: [1, 2, 3] Condition 1: If it is an Odd, should multiply *2. Condition 2: If

Solution 1:

Use .map to transform one array into another - what is returned from each call of the callback function will be the item in the same index in the new array:

constoddToEven = array => array.map(
  num => num % 2 === 1 ? num * 2 : num
);
console.log(oddToEven([1, 2, 3]))

Or, to be more verbose:

functionoddToEven(array) {
  returnarray.map(function(num) {
    if (num % 2 === 1) // Oddreturn num * 2;
    else// Even (or not an integer)return num;
  }
}

Of course, this assumes that every item in the original array is an integer.

Solution 2:

When doing [array] you basically wrap the array into another array, you probably don't need [[1, 2, 3]]. To copy an array, use [...array], however, do you really need three arrays? Wouldn't it be enough to go over the passed array, and change it according to the rules? For that we have to go over the indices of the array:

functionoddToEven(array) {
  for(let i = 0; i < array.length; i++) {
    //...
  }

  returnarray;
}

Now inside that loop, you can get the current element with array[i], and also modify it with array[i] = ? ... You can also check if it is even with

if(array[i] % 2 === 0) {
       // todo
     } else {
       // todo
     }

Solution 3:

In JavaScript we usually use map, filter and reduce to solve this kind of problem in a functional way

functionoddToEven(array) {
    return array.map(n => (n % 2 === 1 ? n * 2 : n));
}

Note that map will crate a new array so your original array will remain the same. Usage:

const originalArray = [1,2,3,4];
const convertedArray = oddToEven(originalArray);
// origianlArray is [1,2,3,4]// convertedArray is [2,2,6,4]

Solution 4:

You can use a simple forEach() loop for that:

var arr = [1, 2, 3, 4, 5, 6, 7];
var res = [];
arr.forEach(function(val){
  if(val % 2 === 0){
   res.push(val); 
  } else {
   res.push(val*2);
  }
});
console.log(res);

Solution 5:

This is how you can modify your own code:

functionoddToEven(arr) {

     return arr.map(function(num){
         return num % 2 === 1 ? num * 2 : num
     });

 }

oddToEven([1,2,3]); // here you need to send the array, not 1, 2, 3

Post a Comment for "Applying Conditions To An Array"