Input: [1, 2, 3] . Output should be [2,3,4] without mutating array. How to make it dynamic as 1 is hardcode given . | JavaScript, Node.js, React.js and Angular.js Forum
J
JYOTI SHARMA Posted on 21/01/2022

Note: Almost done. Only dynamic part(1) is left.

var arr=[1, 2, 3;

var newArray = [];
function map(arr, callback) { // arr=[1, 2, 3], callback=function (x) { return x + 1; }

arr.forEach(function(index,value,arr){


newArray[value] = index + 1; // 1 is hardcode here .

//i = 0;

}

);
console.log(newArray);

// forEach(arr,function(element){element*1});

}


Y
Yogesh Chawla Replied on 21/01/2022

Will this work?

var arr=[1, 2, 3];
var newArray = [];

console.log(arr.map(v=> v + 1));

//or
newArray = arr.map(function(entry) {
  return entry + 1;
});
console.log(newArray);

//or
newArray = [];
arr.forEach(function(x){ newArray.push(x + 1) }); 
console.log(newArray);

//Will this work?


M
Replied on 21/01/2022

You can assign any new incremented value also:

var arr = [1, 2, 3];
var newArray = [];
var incValue = 5;

console.log(arr.map(v => v + incValue));

//or
var arr = [1, 2, 3];
newArray = arr.map(function(entry) {
  return entry + incValue;
});
console.log(newArray);

//or
newArray = [];
arr.forEach(function(x) {
  newArray.push(x + incValue)
});
console.log(newArray);

//Will this work?