I came up with the following solution for returning an array of squared numbers, sorted in ascending order.
function sortedSquaredArray(array) {
let squaredArray = [];
for(i=0;i<array.length;i++){
squaredArray.push(array[i] ** 2);
}
return squaredArray.sort((a,b) => a-b);
}
I'm trying to get better at writing recursions, so I'm attempting to turn the above into a pure recursive function (with no inner function).
This is my attempt.
function sortedSquaredArray(array) {
let squaredArray = [];
squaredArray.push(array[0] ** 2);
if(array.length) sortedSquaredArray(array.shift());
return squaredArray.sort((a,b) => a-b);
}
I believe its the sortedSquaredArray(array.shift())
that's causing this to fail.. I thought about using .slice
and .concat
somehow, but struggling to wrap my head around it.
What am I missing?