How do you modify an array in javascript?

Modify all Elements in an Array #

To change the value of all elements in an array:

  1. Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself.
  2. Use the index of the current iteration to change the corresponding array element.

index.js

Copied!

const arr = ['a', 'b', 'c']; arr.forEach((element, index) => { arr[index] = element + index; }); console.log(arr); // 👉️ ['a0', 'b1', 'c2']

The function we passed to the Array.forEach() method gets invoked with each element, its corresponding index and the entire array.

We used the index to change the value of the array element at the specific position.

We could have achieved the same result by using a plain for loop. However, for loops are a bit more verbose and indirect.

index.js

Copied!

const arr = ['a', 'b', 'c']; for (let index = 0; index < arr.length; index++) { arr[index] = arr[index] + index; } console.log(arr); // 👉️ ['a0', 'b1', 'c2']

It's a matter of personal preference, but in my opinion the forEach() approach is more readable and intuitive.

Most experienced developers avoid mutating arrays and objects. Instead, they create new arrays containing the desired elements. We can use the map method to achieve this.

index.js

Copied!

const arr = ['a', 'b', 'c']; const newArr = arr.map((element, index) => { return element + index; }); console.log(newArr); // 👉️ ['a0', 'b1', 'c2'] console.log(arr) // 👉️ ['a', 'b', 'c']

We used the Array.map method in a very similar way to how we used the forEach method.

However, this time we don't change the elements in the original array. Instead, we create a new array containing the modified elements.

Code gets very hard to follow if we mutate the contents of an array multiple times. In my experience, a better approach is to create a new array that only contains the elements we need.

Further Reading #

  • Trim all Strings in an Array using JavaScript
  • Set all Array Elements to a Specific Value in JavaScript
  • Convert a String to Array of Numbers in JavaScript
  • Convert all Array Elements to Lowercase in JavaScript
  • Convert all Array Elements to Uppercase in JavaScript
  • Check if Multiple Values exist in Array in JavaScript
  • Capitalize the First Letter of Each Word in Array in JS

To add or delete elements entirely which would alter the index, by way of extension of zhujy_8833 suggestion of slice() to iterate over a copy, simply count the number of elements you have already deleted or added and alter the index accordingly. For example, to delete elements:

let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
    if (value === "A2" || value === "A5") {
        values.splice(index - count++, 1);
    };
});
console.log(values);

// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]

To insert elements before:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - count--, 0, 'newVal');
};

// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]

To insert elements after:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - --count, 0, 'newVal');
};

// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']

To replace an element:

if (value === "A3" || value === "A4" || value === "A7") {
    values.splice(index, 1, 'newVal');
};

// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]

Note: if implementing both 'before' and 'after' inserts, code should handle 'before' inserts first, other way around would not be as expected

How do you modify an array?

To change the value of all elements in an array: Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

Can an array be modified?

No problem—you can modify the values in arrays as easily as other variables. One way is to access an element in an array simply by referring to it by index.

How do you change an element in an array?

To replace an element in an array: Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

How do you manipulate an array of objects in JavaScript?

Our function should search the first array for objects with the same "id" property that is present in the second array. Then our function should replace the "name" property of those objects with the corresponding "name" property of the second array's objects.