1
var i = [1,2,3,4,6,7];
var k = i.map( (data, i) => { if(data==1) return 2; else return data; } );
console.log(k);

This program is going to output [2,2,3,4,6,7]

I am changing value of k based on a specific value. How can i change the value according to a specific array index using map function?

like how we do normally, array[index] = somevalue;

7
  • why do you need to iterate if you have already an index for changing? Commented Mar 14, 2017 at 20:14
  • Couldn't you just change if(data==1) to if(i==1)... Commented Mar 14, 2017 at 20:14
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Mar 14, 2017 at 20:14
  • If you are only changing a specific array index, just clone the array and then set that particular element. k=i.slice(); k[index] = somevalue; Commented Mar 14, 2017 at 20:15
  • if(i ==1) … Commented Mar 14, 2017 at 20:15

1 Answer 1

1

You could check with the index of the array while iterating, with the wanted index and return a selected value or the original value.

var array = [1, 2, 3, 4, 6, 7],
    index = 3,
    result = array.map((a, i) => i === index ? 42 : a);

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.