Modify Array Elements in JavaScript

19 min read·Jan 1, 2025

To modify the value of an array element, you can specify its index in brackets and use the assignment operator as follows:

array[index] = new_value;

Example

📚 Definition: The Bubble Sort algorithm is a simple sorting algorithm which consists in repeatedly comparing and swapping adjacent elements if they are in the wrong order, effectively "bubbling" the largest unsorted element to its correct position in each pass until the entire list is sorted.

For example, here is the list of transformations the algorithm would perform in order to sort the array containing [3, 2, 1]:

[3, 2, 1] => [2, 3, 1] => [2, 1, 3] => [1, 2, 3]

Note: In programming, variable swapping is usually done through a third temporary variable:

let a = 1;
let b = 3;
let tmp;

tmp = a;   // Store the value of `a`.
a = b;     // Override the value of `a` with the value of `b`.
b = tmp;   // Override the value of `b` with the value of `tmp`.

Let's consider this script, that uses the Bubble Sort algorithm to sort the elements of an array in ascending order:

function bubbleSort(array) {
  console.log(array);

  for (let i = 0 ; i < array.length ; i++) {
    for (let j = 0 ; j < array.length - 1 ; j++) {
      if (array[j] > array[j + 1]) {
        let tmp = array[j];

        array[j] = array[j + 1];
        array[j + 1] = tmp;

        console.log(array);
      }
    }
  }

  return array;
}

const numbers = [3, 5, 1, 8, 2];

bubbleSort(numbers);

When executed, the bubbleSort function will:

  1. Output the initial value of the array parameter.
  2. Start a first for loop that iterates once on each index of the array.
  3. Start a second for loop in charge of comparing and swapping unordered elements.
  4. Check whether the value of the current index is greater than the next one.
  5. Save the value of the current index into a temporary variable to prevent it from being overwritten in the next step.
  6. Assign the value of the next index to the current index.
  7. Assign the temporarily saved value of the current index to the next index.
  8. Output the current value of the array.
  9. Repeat the loops.
  10. Return the sorted array.

Which will produce this output:

[ 3, 5, 1, 8, 2 ]
[ 3, 1, 5, 8, 2 ]
[ 3, 1, 5, 2, 8 ]
[ 1, 3, 5, 2, 8 ]
[ 1, 3, 2, 5, 8 ]
[ 1, 2, 3, 5, 8 ]

Reassign subarray elements

To modify the value of a nested array element, you can specify its index in brackets and use the assignment operator as follows:

array[indexA][...][indexN] = new_value;

Example

Let's consider this script, that implements a basic version of the tic-tac-toe game:

let board = [
  [' ', ' ', ' '],
  [' ', ' ', ' '],
  [' ', ' ', ' ']
];
let player = 1;

function displayBoard() {
  console.log('-----------------');
  console.log(board[0]);
  console.log(board[1]);
  console.log(board[2]);
  console.log('-----------------');
}

function addPosition(x, y) {
  board[x][y] = player === 1 ? 'O' : 'X';
}

function switchPlayer() {
  player = player === 1 ? 2 : 1;
}

function play(x, y) {
  addPosition(x, y);
  switchPlayer();
  displayBoard();
}

play(1, 2);
play(2, 1);
play(2, 2);

When executed, it will:

  1. Invoke the play function in charge of adding the played position into the grid, switching the player, and outputting the grid.
  2. Invoke the addPosition function in charge of updating the index y of the subarray x stored in the board variable with the 'O' or 'X' character, respectively representing the player 1 or 2.
  3. Invoke the switchPlayer function in charge of updating the value stored in the player variable representing the current player.
  4. Invoke the displayBoard function in charge of outputting the array stored in the board variable line by line.

Which will produce this output:

-----------------
[ ' ', ' ', ' ' ]
[ ' ', ' ', 'O' ]
[ ' ', ' ', ' ' ]
-----------------
-----------------
[ ' ', ' ', ' ' ]
[ ' ', ' ', 'O' ]
[ ' ', 'X', ' ' ]
-----------------
-----------------
[ ' ', ' ', ' ' ]
[ ' ', ' ', 'O' ]
[ ' ', 'X', 'O' ]
-----------------

Add elements to arrays

Arrays are dynamic in nature, which means that values can be added even after their creation.

To add a new element at the beginning of an array, you can use the .unshift() method of the array instance, which will automatically shift all the indexes of the array:

array.unshift(value);

On the other hand, to add a new element at the end of an array, you can use the .push() method of the array instance:

array.push(value);

Example

Let's consider this script, that adds participants to a virtual queue based on their vip status:

const participants = [
  { id: 1, name: 'John Doe', vip: false },
  { id: 2, name: 'Jane Dark', vip: true },
  { id: 3, name: 'Jack Flare', vip: false },
  { id: 4, name: 'Emily Blyke', vip: false },
  { id: 5, name: 'Johnson Faust', vip: true }
];
let queue = [];

for (let participant of participants) {
  const { id, name, vip } = participant;

  if (vip) {
    queue.unshift({ id, name });
  } else {
    queue.push({ id, name });
  }
}

console.log(queue);

When executed, it will:

  1. Loop on each element of the participants array.
  2. Extract the id, name, and vip properties from the current element using the object destructuring syntax {}.
  3. Check whether the vip property is set to true.
  4. Add the current element's id and name properties to the beginning of the queue array if it is true.
  5. Add the current element's id and name properties to the end of the queue array if it is true.

Which will produce this output:

[
  { id: 5, name: 'Johnson Faust' },
  { id: 2, name: 'Jane Dark' },
  { id: 1, name: 'John Doe' },
  { id: 3, name: 'Jack Flare' },
  { id: 4, name: 'Emily Blyke' }
]

Extract elements from arrays

To extract the first element from an array, which implies removing it from the array, you can use the .shift() method of the array instance:

variable = array.shift();

On the other hand, to extract the last element from an array, which also implies removing it from the array, you can use the .pop() method of the array instance:

variable = array.pop();

Example

Let's consider this script:

let list = [
  "first",
  "second",
  "third"
];
let item;

console.log(list);

item = list.shift();

console.log(list, '=>', item);

item = list.pop();

console.log(list, '=>', item);

When executed, it will:

  1. Declare a variable named list and initialize it with an array containing 3 strings.
  2. Remove the first element from the list array, store it into the item variable, and output its value.
  3. Remove the last element from the list array, store it into the item variable, and output its value.

Which will produce this output:

[ 'first', 'second', 'third' ]
[ 'second', 'third' ] => first
[ 'second' ] => third

Enjoying the courses?

I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:

Support BackendBrewery
Modify Array Elements in JavaScript | Backend Brewery