I'm trying to learn how to refactor my code, and I have written the following function block:
joinSame = (arr) =>{
let simplifiedArr = [];
for(let i=0; i < arr.length; i++){
const tempLast = arr.lastIndexOf(arr[i]);
const element = arr[i].toString()
if(i === tempLast){
simplifiedArr.push(element);
} else {
const tempMultiplier = tempLast-i+1;
simplifiedArr.push(element.repeat(tempMultiplier));
i = tempLast;
}
}
return simplifiedArr;
}
The idea is that if I input a sorted array ([3,3,3,4,'a','a']), I want the output to be an array with similar entities combined into a string (['333', '4', 'aa']). I tried to use the .map and .forEach array method, but my problem is trying to "hop" the index to go to the next unique element.
Am I overcomplicating things by trying to get it to refactor to a .map or .forEach method, or is my code "good" enough to let it go?