w3resource

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.

The program extracts the middle elements from two arrays, each with a length of 3, and creates a new array containing these middle elements.

Visual Presentation:

JavaScript: Create a new array taking the middle elements of the two arrays of integer and each length 3.

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:

Flowchart: JavaScript - Create a new array taking the middle elements of the two arrays of integer and each length 3

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/javascript-exercises/javascript-basic-exercise-75.php