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:
- Output the initial value of the
arrayparameter. - Start a first
forloop that iterates once on each index of the array. - Start a second
forloop in charge of comparing and swapping unordered elements. - Check whether the value of the current index is greater than the next one.
- Save the value of the current index into a temporary variable to prevent it from being overwritten in the next step.
- Assign the value of the next index to the current index.
- Assign the temporarily saved value of the current index to the next index.
- Output the current value of the array.
- Repeat the loops.
- 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:
- Invoke the
playfunction in charge of adding the played position into the grid, switching the player, and outputting the grid. - Invoke the
addPositionfunction in charge of updating the indexyof the subarrayxstored in theboardvariable with the'O'or'X'character, respectively representing the player1or2. - Invoke the
switchPlayerfunction in charge of updating the value stored in theplayervariable representing the current player. - Invoke the
displayBoardfunction in charge of outputting the array stored in theboardvariable 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:
- Loop on each element of the
participantsarray. - Extract the
id,name, andvipproperties from the current element using the object destructuring syntax{}. - Check whether the
vipproperty is set totrue. - Add the current element's
idandnameproperties to the beginning of thequeuearray if it istrue. - Add the current element's
idandnameproperties to the end of thequeuearray if it istrue.
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:
- Declare a variable named
listand initialize it with an array containing 3 strings. - Remove the first element from the
listarray, store it into theitemvariable, and output its value. - Remove the last element from the
listarray, store it into theitemvariable, 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