w3resource

JavaScript: Replace all the numbers with a specified number of a given array of integers

JavaScript Basic: Exercise-95 with Solution

Write a JavaScript program to replace all numbers with a specified number in an array of integers.

Visual Presentation:

JavaScript: Replace all the numbers with a specified number of a given array of integers.

Sample Solution:

JavaScript Code:

// Function to replace a specified element in an array with a new value
function array_element_replace(arr, old_value, new_value) {
  for (var i = 0; i < arr.length; i++) {
    // Check if the current element is equal to the old value
    if (arr[i] === old_value) {
      arr[i] = new_value;  // Replace the old value with the new value
    }
  }
  return arr;  // Return the modified array
}

// Example usage
num = [1, 2, 3, 2, 2, 8, 1, 9];  // Original array
console.log("Original Array: " + num);
console.log(array_element_replace(num, 2, 5));  // Replace 2 with 5 in the array

Output:

Original Array: 1,2,3,2,2,8,1,9
[1,5,3,5,5,8,1,9]

Live Demo:

See the Pen javascript-basic-exercise-95 by w3resource (@w3resource) on CodePen.


Flowchart:

Flowchart: JavaScript - Replace all the numbers with a specified number of a given array of integers

ES6 Version:

// Function to replace all occurrences of a specified value in an array
const array_element_replace = (arr, old_value, new_value) => {
    // Iterate through the array
    for (let i = 0; i < arr.length; i++) {
        // Check if the current element is equal to the old value
        if (arr[i] === old_value) {
            arr[i] = new_value;  // Replace with the new value
        }
    }
    return arr;  // Return the modified array
};

let num = [1, 2, 3, 2, 2, 8, 1, 9];  // Example array
console.log("Original Array: " + num);
console.log(array_element_replace(num, 2, 5));

Improve this sample solution and post your code through Disqus.

Previous: JavaScript program to find the number which appears most in a given array of integers.
Next: JavaScript program to compute the sum of absolute differences of consecutive numbers of a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.