javascript modify array in place code example

Example 1: foreach and replace item based on condition

arr.forEach(function(part, index, theArray) {
  theArray[index] = "hello world";
});

Example 2: modify array elements javascript

Using a FOR loop, write a function addNumber which adds the argument n to each 
number in the array arr and returns the updated arr:
const addNumber=(arr, n)=>{  
  let arr1=[];
  for(let i=0;i<Math.max(arr.length);i++){
    arr1.push((arr[i]||0)+n)
  }
  return arr1;
} 
console.log(addNumber([4, 5, 6], 7)); // expected log [11, 12, 13]

Example 3: modify array js

let newArray = oldArray.map(funcToEachElem);

Example 4: 6 ways to modify an array javascript

let browsers = ['chrome', 'firefox', 'edge'];
browsers.unshift('safari');
// add an element at the beginning of array
console.log(browsers); //  ["safari", "chrome", "firefox", "edge"]

let browsers = ['chrome', 'firefox', 'edge'];
browsers.push('safari');
// add an element at the end of array
console.log(browsers); //  ["chrome", "firefox", "edge", "safari"]

let browsers = ['chrome', 'firefox', 'edge'];
browsers.shift(); 
// Delete first element of array
console.log(browsers); // ["firefox", "edge"]

let browsers = ['chrome', 'firefox', 'edge'];
browsers.pop(); 
//delete last elemnent of array
console.log(browsers); // ["chrome", "firefox"]

// Add and remove anywhere you want
//Add
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction() {
  fruits.splice(3, 0, "Lemon", "Kiwi");
//fruits.splice(Where to add, what to delete, "Lemon", "Kiwi");
   document.getElementById("demo").innerHTML = fruits;
}
//output Banana,Orange,Apple,Lemon,Kiwi,Mango

//Delete
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction() {
  fruits.splice(2, 1);
// fruits.splice(where to delete, how many);
  document.getElementById("demo").innerHTML = fruits;
}// output: Banana,Orange,Mango

Example 5: how to modify an array

let schedule = ['I', 'have', 'a', 'meeting', 'with'];
// adds 3 new elements to the array
schedule.splice(5, 0, 'some', 'clients', 'tommorrow');
console.log(schedule); 
// ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]