JavaScript: Create a new array taking the middle elements of the two arrays of integer and each length 3
JavaScript Basic: Exercise-75 with Solution
Write a JavaScript program to create an array taking the middle elements of the two arrays of integer and each length 3.
Visual Presentation:
Sample Solution:
JavaScript Code:
// Define a function named middle_elements that takes two arrays, 'a' and 'b', as parameters
function middle_elements(a, b) {
// Create a new array named 'new_array'
var new_array = [];
// Push the second elements of both arrays into the new_array
new_array.push(a[1], b[1]);
// Return the new_array
return new_array;
}
// Call the function with sample arguments and log the results to the console
console.log(middle_elements([1, 2, 3], [1, 5, 6])); // Output: [2, 5]
console.log(middle_elements([3, 3, 3], [2, 8, 0])); // Output: [3, 8]
console.log(middle_elements([4, 2, 7], [2, 4, 5])); // Output: [2, 4]
Output:
[2,5] [3,8] [2,4]
Live Demo:
See the Pen JavaScript - Create a new array taking the middle elements of the two arrays of integer and each length 3 - basic-ex-75 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
// Define a function named middle_elements that takes two arrays (a and b) as parameters
const middle_elements = (a, b) => {
// Create a new array and push the second element of each input array
const new_array = [a[1], b[1]];
// Return the new array
return new_array;
};
// Call the function with sample arguments and log the results to the console
console.log(middle_elements([1, 2, 3], [1, 5, 6])); // Output: [2, 5]
console.log(middle_elements([3, 3, 3], [2, 8, 0])); // Output: [3, 8]
console.log(middle_elements([4, 2, 7], [2, 4, 5])); // Output: [2, 4]
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to find the larger value between the first or last and set all the other elements with that value.
Next: JavaScript program to create a new array taking the first and last elements from a given array of integers and length must be greater or equal to 1.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics