-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_sentence.js
41 lines (34 loc) · 1.06 KB
/
reverse_sentence.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//reverse each word in the sentence, but keep the words in order.
//ex: abc def -> cba fed
function reverseSentence(str){
//split into arrays on spaces
let array = str.split(' '); //'abc def' -> [abc, def]
let reverseArr = [];
var revArr = [];
array.forEach(arr => {
let newArr = arr.split(''); //abc -> [a,b,c]
let revStr = '';
/*
let revNewArr = [];
console.log(newArr);
newArr.forEach(ch =>{
revNewArr.unshift(ch);
})
console.log(revNewArr);
let revNewStr = revNewArr.join('');
console.log (revNewStr);
reverseArr.push(revNewStr);
*/
for (let i = newArr.length-1; i >= 0; i--){
revStr += newArr[i];
}
revArr.push(revStr);
})
console.log(revArr);
let reversedSentence = revArr.join(' ');
console.log(reverseArr);
//reversedSentence = reverseArr.join(' ');
return reversedSentence;
}
let reversed = reverseSentence('abc def');
console.log(reversed);