-1

I am interested to discover how I can pass an if clause to the map function. For example, how I can check if the element is 0 then add 2 to the element and then do the rest of calculation

var array1 = [1, 4, 0, 16, 0, 8];

const map1 = array1.map(x => x * 2);

console.log(map1);
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

5 Answers5

3

Use a ternary operator:

var array1 = [1, 4, 0, 16, 0, 8];

const map1 = array1.map(x => (x == 0 ? x + 2 : x) * 2);

console.log(map1);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
1

It may help looking at the ‘longhand’ version:

This:

var array1 = [1, 4, 0, 16, 0, 8];

const map1 = array1.map(x => x * 2);

console.log(map1);

is the same as:

var array1 = [1, 4, 0, 16, 0, 8];

const map1 = array1.map(function(x) {

  return x * 2;

});

console.log(map1);

therefore to reference and modify the value being processed in your map function, you can use:

var array1 = [1, 4, 0, 16, 0, 8];

const map1 = array1.map(function(x) {

  if (x === 0) {
    x += 2;
  }
  return x * 2;

});

console.log(map1);

or if using arrow function syntax:

var array1 = [1, 4, 0, 16, 0, 8];

const map1 = array1.map(x => {

  if (x === 0) {
    x += 2;
  }
  return x * 2;

});

console.log(map1);

Here are MDN web docs on map():

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

It might also be helpful to search for a few articles on “arrow functions”, like this one:

https://flaviocopes.com/javascript-arrow-functions

user1063287
  • 10,265
  • 25
  • 122
  • 218
0

TL;DR Pass a function into map and return your x;

var array1 = [1, 4, 0, 16, 0, 8];
    
const map1 = array1.map(x => {
    if (x === 0) {
        x += 2;
    }
    return x * 2
});

console.log(map1);

x => x*2 can write as x => { return x*2; }. Because it's a function, you can execute some extra calculation (or condition) in the beginning of the function.

NoobTW
  • 2,466
  • 2
  • 24
  • 42
0

Not 100% what logic you're trying to implement, but if it's "multiply by 2 if x != 0, add by 2 if x == 0", try:

  var array1 = [1, 4, 0, 16, 0, 8]
  const map1 = array1.map(x => (x == 0 ? x + 2 : x * 2))
  console.log(map1)

  // [2, 8, 2, 32, 2, 16]

-1
var array1 = [1, 4, 0, 16, 0, 8];
for (var i = 0; i < array1.length; i++) {
  if (array1[i] == 0) {
    array[i] = array[i] + 2;
  }
}
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
t hj
  • 93
  • 4