130,469 views
2 votes
2 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.

User Kevin Law
by
3.3k points

1 Answer

23 votes
23 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 Tarun Dugar
by
3.1k points