Reverse Array, Let Elements in New Array Equal Length of Original Array Elements - JavaScript
First construct the full reversed string, eg
!eiltonnacIdnasttubgibekilI
Then, from an array of the initial lengths (which can be done with a .map
in advance), iterate over that array and slice
that length from the reversed string, and push to an array:
function ultimateReverse(array) {
const lengths = array.map(({ length }) => length);
let reversedStr = [...array.join("")].reverse().join('');
const result = [];
lengths.forEach((length) => {
result.push(reversedStr.slice(0, length));
reversedStr = reversedStr.slice(length);
});
return result;
}
console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));
You could also keep the initial reversed data as an array that you splice
from, instead of reassigning reversedStr
:
function ultimateReverse(array) {
const lengths = array.map(({ length }) => length);
const reversedChars = [...array.join('')].reverse();
return lengths.map(
length => reversedChars.splice(0, length).join('')
);
}
console.log(ultimateReverse(["I", "like", "big", "butts", "and", "I", "cannot", "lie!"]));