Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change elements inside and array

How can I get the "e" elements inside of "arr" to be replaced by change0?

The arr array will be an input by the user and I need to change it there is no way to predict which element will be "e".

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];

var change0 = 2

var change1 = 1

document.write(arr);
like image 341
Péter Szabó-tóth Avatar asked Apr 16 '17 10:04

Péter Szabó-tóth


1 Answers

You could use map() method and this will return new updated array and save original.

var arr = [ "a", "b", "c", "d", "e", "f", "g", "h", "e", "j", "e"];
var change0 = 2;

var result = arr.map(e => e == 'e' ? change0 : e);
console.log(result)
like image 94
Nenad Vracar Avatar answered Sep 29 '22 09:09

Nenad Vracar