exception-io
exception-io

Reputation: 115

Unexpected results from array.map()

Very simple question but I couldn't figure why the below code results in NaN in first index?

    var arr = [1, 2, 3, 4];
    var result = arr.map(function(x) {
        if(arr[x] >= 2) {
            return arr[x] + 10;
        } else {
            return arr[x] - 10;
        }
    });

    console.log(result); // [-9, 12, 13, NaN]

Upvotes: 0

Views: 104

Answers (6)

Mikulas
Mikulas

Reputation: 417

x in your code is actually referencing an item of your array, not an index.

You can re-write your code as follows:

var arr = [1, 2, 3, 4]
var result = arr.map( x => (x >= 2) ? x+10 : x-10 )
console.log(result)  // [-9, 12, 13, 14]

Upvotes: 0

Mannu
Mannu

Reputation: 11

var arr = [1, 2, 3, 4];
var result = arr.map(function(val, indx) {
    if(arr[indx] >= 2) {
        return arr[indx] + 10;
    } else {
        return arr[indx] - 10;
    }
});

You need to use index not value

or you can do it like a pro

 const result = arr.map((val, indx) => {
      return  (val >= 2) ? val+10 : val -10       
    });

Upvotes: 0

brk
brk

Reputation: 50291

Array map accepts parameter as (item,index). In your case x is representing array element which will be 1,2,3,4 and so on. So arr[1] will be first element that is 1, but arr[4] will be undefined since there is no element present at the fifth index. You can replace arr[x] with only x or with arr[index]

var arr = [1, 2, 3, 4];
var result = arr.map(function(x, index) {
  console.log('Array element', x)
  if (arr[index] >= 2) {
    return arr[index] + 10;
  } else {
    return arr[index] - 10;
  }
});

console.log(result);

Upvotes: 1

Sabee
Sabee

Reputation: 1811

js map function iterate the elements (in your case) not the indexes. Your x varriable is the current element in iteration

    var arr = [1, 2, 3, 4];
    var result = arr.map(function(x) {
        if(x >= 2) {
            return x + 10;
        } else {
            return x - 10;
        }
    });
   
    console.log(result); 

Upvotes: 0

random
random

Reputation: 7891

If you want to use the index, then in map it is second parameter. The first parameter is the array element.

var arr = [1, 2, 3, 4];
var result = arr.map(function(x, i) {
    if(arr[i] >= 2) {
        return arr[i] + 10;
    } else {
        return arr[i] - 10;
    }
});

console.log(result); // [12, 13, 14, NaN]

But, there is no necessity of index to access the array element.

var arr = [1, 2, 3, 4];
var result = arr.map(function(x, i) {
    if(x >= 2) {
        return x + 10;
    } else {
        return x - 10;
    }
});

console.log(result); // [12, 13, 14, NaN]

Upvotes: 0

Avin Kavish
Avin Kavish

Reputation: 8937

The first argument of the callback is set to the element of the array

var arr = [1, 2, 3, 4];
var result = arr.map(function(x) {
    if(x >= 2) {
        return x + 10;
    } else {
        return x - 10;
    }
});

console.log(result)

Upvotes: 0

Related Questions