I have an array which I want to reverse like
['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];
I want to reverse it like this
["I", " ", "e", "v", "o", "l", " ", "h", "t", "r", "a", "E"]
The problem is I can reverse it using array.slice().reverse(); but it reverses the whole array and I want to reverse after where is space.
Well, some dirty solution may be similar to this one:
var sentence = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];
var reversed = sentence.join('').split(' ').map(word => word.split('').reverse().join('')).join(' ').split('');
console.log(reversed);
You can make it a string, then split and flatMap
const arr = ['I', ' ', 'l', 'o', 'v', 'e', ' ', 'E', 'a', 'r', 't', 'h'];
const res = arr
.join('')
.split(' ')
.flatMap(e => (e + ' ').split('').reverse())
.slice(1);
console.log(res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With