Replace an Integer in an Array With JavaScript

In this post, I’ll walk through the common JavaScript algorithm challenge of replacing an integer in an array.

We’ll start by reviewing the JS challenge itself and then describe an example of how it should work. After that, we’ll take a look at the solution and then walk through it by breaking it down into three steps.

JavaScript algorithm challenge

Given an array of integers, replace all the occurrences of the elemToReplace with the substitutionElem.

Example of how it should work

For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 2, the output should be arrayReplace(inputArray, elemToReplace, substititionElem) = [3, 2, 3].

Solution

let arr = [1, 2, 1] // test array

function arrayReplace(array, elemToReplace, substitutionElem) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] === elemToReplace) {
            array[i] = substitutionElem }
        } 
    return array
}

arrayReplace(arr, 1, 3) // returns [3, 2, 3]

I’ve also set up this working solution on Codepen.io.

Solution Explained

To solve this JavaScript algorithm challenge, we’ll need to iterate through each item in a given array using a for loop.

Then, inside the for loop, we’ll need to set up an if statement to execute on the condition that if an item is equal to the element we need to replace, then it should be replaced with the substitution element.

After writing our logic inside of the for loop and the if statement, we’ll write a return statement to end the function and return a value.

Step 1 – The for loop

To solve this JavaScript algorithm challenge, we’ll need to iterate through each item in a given array using a for loop. Here’s how we would set that up:

for ([initialExpression]; [conditionExpression]; [incrementExpression]) {
  statement
}

Now, plug in each expression like so:

for (let i = 0; i < array.length; i++) {
// more code goes here
}

First, we set the initial expression. The initial expression is the number we want to start counting at. So, we need to set our counter value set to 0 since JavaScript arrays are zero-indexed and we want to start counting from there.

Second, we need to set the condition expression. This is the logic we need to set up for the increment expression. Inside the condition expression, we’ll need to know how long the array is. For determining the length of the array, we can use .length property on our array.

So, right now, we’ve set our counter to 0 and have the condition expression set to execute if i is less than the length of the array.

The third thing we need to do is set the increment expression. This is the logic we need to write to actually make the for loop count from our initial expression of 0 through the length of the array.

In our increment expression i++, we’re saying we need to increment the counter by 1 as long as the counter is less than the length of the array.

In other words, we want the for loop counter to increment by 1 for every index in the array.

Read more on for loops on MDN Web Docs.

Step 2 – The if statement

After the for loop is set up, inside of the for loop, we’ll need to use an if statement. Our if statement is composed of two parts: a condition and a statement.

if (condition) {
    statement1
}

Condition

In the condition, we will check if any item in the array is equal to the elemToReplace.

To do this, first, we need to access each index of the array by using bracket notation array[i]. Each time the for loop executes, the value of i is then referenced in array[i].

Now that we have access to each index, we can check if each item in the array is strictly equal to the element that needs to be replaced. We can do that using the strict equality operator ===. See how the condition is set up below.

if (array[i] === elemToReplace) {
  statement
}

Read more on if … else statements on MDN Web Docs.

Statement

Next, we need to write a statement to execute if the condition is met. We need to write what we want to happen if the condition is true. So, in the context of this challenge, we need to target the item in the array that is equal to the elemToReplace and then replace it with the substitutionElem.

Since the if statement will only execute if the item in the array is equal to the elemToReplace, we can use array[i] to reference and target every elemToReplace.

From here, we’ll need to reassign each elemToReplace with the substititionElem. See how that’s set up below.

array[i] = substitutionElem

This statement completes our logic of finding a specific integer in an array and replacing it (by re-assigning it) with the substitution element.

Step 3 – The return statement

The final step is to return the array after the function works through the logic: for every item in a given array, if the item (the elemToReplace) matches a substititionElem, replace it. Our return statement’s job is to return the array after the function is done iterating through and replacing each elemToReplace with substititionElem.

We write the return statement and target the array like so:

function arrayReplace(array, elemToReplace, substitutionElem) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] === elemToReplace) {
        array[i] = substitutionElem
        }
    }
    return array
}

Read more on the return statement on MDN Web Docs.

Checking to see if it works

To check to see if this function is working as expected, try it out with your own array or copy and paste my solution example into your favorite code sandbox (i.e. codepen.io).

let arr = [1, 2, 1] // test array

function arrayReplace(array, elemToReplace, substitutionElem) { 
    for (let i = 0; i < array.length; i++) { 
        if (array[i] === elemToReplace) { 
        array[i] = substitutionElem } 
        }
    return array 
} 

arrayReplace(arr, 1, 3) // returns [3, 2, 3]

Now you know how to replace an integer in an array with JavaScript!

I’ve enjoyed breaking down this JavaScript algorithm challenge and hope this write-up helped you understand it better.



Categories