62.0k views
4 votes
Reverse Word Order: Write a program that reverses the order of the words in a given sentence. This program requires reversing the order of the words wherein the first and last words are swapped, followed by swapping the second word with the second to last word, followed by swapping the third word and the third to last words, and so on.

1 Answer

6 votes

Answer:

function reverseArray(arr) {

if (arr.length > 1) {

arr = [arr[arr.length-1], ...reverseArray(arr.slice(1, -1)), arr[0]]

}

return arr;

}

function reverseSentence(sentence) {

let words = reverseArray( sentence.split(" ") );

return words.join(" ");

}

console.log( reverseSentence("The quick brown fox jumps over the lazy dog's back") );

console.log( reverseSentence("one two three") );

console.log( reverseSentence("one two") );

console.log( reverseSentence("Single") );

Step-by-step explanation:

This is a solution in javascript leveraging several powerful constructs in that language, such as the spread operator.

User DotNet NF
by
5.2k points