0

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?

1 Answer 1

2

You can make use of reduce and then take Object.values:

const arr = [3,3,3,4,'a','a'];
const result = Object.values(arr.reduce((a,b)=>(a[b]=(a[b] || '')+b,a),{}))

console.log(result);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I thought the reduce method only gave one value for the output. Looks like I need to study that one more along with Object.values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.