Discover a world of knowledge at Westonci.ca, where experts and enthusiasts come together to answer your questions. Find reliable answers to your questions from a wide community of knowledgeable experts on our user-friendly Q&A platform. Experience the ease of finding precise answers to your questions from a knowledgeable community of experts.

Write a method swapArrayEnds() that swaps the first and last elements of its array parameter. Ex: sortArray

Sagot :

I understand you want a function that swaps the first and last element of an array so that the first element takes the last one's value and vice versa.

Answer and Explanation:

Using Javascript programming language:

function swapArrayEnds(sortArray){

var newArray= sortArray.values();

var firstElement=newArray[0];

newArray[0]=newArray[newArray.length-1];

newArray[newArray.length-1]=firstElement;

return newArray;

}

var exampleArray=[2, 5, 6, 8];

swapArrayEnds(exampleArray);

In the function above we defined the swapArray function by passing an array parameter that is sorted by swapping its first and last element. We first get the elements of the arrayvusing the array values method. We then store the value of the first element in the variable firstElement so that we are able to retain the value and then switch the values of the first element before using the firstElement to switch value of the last element. We then return newArray and call the function.