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 the numbers with a specified number of a given array of integers.

Pictorial Presentation:

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

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Replace all the numbers with a specified number of a given array of integers</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function array_element_replace(arr, old_value, new_value) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === old_value) {
      arr[i] = new_value;
    }
  }
  return arr;
}
num = [1, 2, 3, 2, 2, 8, 1, 9];
console.log("Original Array: "+num);
console.log(array_element_replace(num, 2, 5));

Sample Output:

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

Flowchart:

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

ES6 Version:

function array_element_replace(arr, old_value, new_value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === old_value) {
      arr[i] = new_value;
    }
  }
  return arr;
}
num = [1, 2, 3, 2, 2, 8, 1, 9];
console.log(`Original Array: ${num}`);
console.log(array_element_replace(num, 2, 5));

Live Demo:

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


Contribute your code and comments through Disqus.

Previous: Write a JavaScript program to find the number which appears most in a given array of integers.
Next: Write a 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?



JavaScript: Tips of the Day

Parameter's value

function getItems(fruitList, ...args, favoriteFruit) {
  return [...fruitList, ...args, favoriteFruit]
}

getItems(["banana", "apple"], "pear", "orange")

...args is a rest parameter. The rest parameter's value is an array containing all remaining arguments, and can only be the last parameter! In this example, the rest parameter was the second parameter. This is not possible, and will throw a syntax error.

function getItems(fruitList, favoriteFruit, ...args) {
  return [...fruitList, ...args, favoriteFruit];
}


getItems(['banana', 'apple'], 'pear', 'orange');
The above example works. This returns the array [ 'banana', 'apple', 'orange', 'pear' ].

Ref: https://bit.ly/3jFRBje