JavaScript: Find the larger value between the first or last and set all the other elements with that value
JavaScript Basic: Exercise-74 with Solution
Write a JavaScript program to find the largest value between the first and last elements and set all the other elements to that value. Display the updated array.
The program compares the first and last elements of an array and sets all other elements to the larger of these two values. It then displays the updated array with all elements either equal to the first or last element, whichever is larger.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named all_max that takes an array of numbers as a parameter
function all_max(nums)
{
// Determine the maximum value between the first and third elements using a ternary operator
var max_val = nums[0] > nums[2] ? nums[0] : nums[2];
// Set all elements in the array to the determined maximum value
nums[0] = max_val;
nums[1] = max_val;
nums[2] = max_val;
// Return the modified array
return nums;
}
// Call the function with sample arguments and log the results to the console
console.log(all_max([20, 30, 40])); // Output: [40, 40, 40]
console.log(all_max([-7, -9, 0])); // Output: [0, 0, 0]
console.log(all_max([12, 10, 3])); // Output: [12, 12, 12]
Output:
[40,40,40] [0,0,0] [12,12,12]
Live Demo:
See the Pen JavaScript - Find the larger value between the first or last - basic-ex-74 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Define a function named all_max that takes an array (nums) as a parameter
const all_max = (nums) => {
// Use the spread operator to create a copy of the array, then find the maximum value
const max_val = Math.max(...nums);
// Update all elements of the array with the maximum value
nums[0] = max_val;
nums[1] = max_val;
nums[2] = max_val;
// Return the modified array
return nums;
};
// Call the function with sample arguments and log the results to the console
console.log(all_max([20, 30, 40])); // Output: [40, 40, 40]
console.log(all_max([-7, -9, 0])); // Output: [0, 0, 0]
console.log(all_max([12, 10, 3])); // Output: [12, 12, 12]
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to reverse the elements of a given array of integers length 3.
Next: JavaScript program to create a new array taking the middle elements of the two arrays of integer and each length 3.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-74.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics