Javascript - . map()

Asked

Viewed 72 times

1

Good morning guys, I have an array, however I only want to multiply the array index 2 using .map(). Below is an example where I am multiplying all array positions.

const nums = [1,2,3,4,5]

let result = nums.map(function(e, i, arr) {
    return e * 2 
})
console.log(result)

How to modify position 2 only?

  • Please check the replies and tick one as the response to your post ...

1 answer

2

If you just want to modify the Indice 2 just do so:

nums[2] = nums * 2;

So you change the internal value of the array without needing to reassign. If you want to use .map() which is the best solution you can often do so:

let result = nums.map(function(e, i, arr) {
    return i === 2 ? e * 2 : e; 
})
  • Good!!! very good, that’s what I wanted to learn! Thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.