Search code examples
javascriptnode.jsreduce

single line reduce statement not working - how to fix


when i try to use commented code (multi line reduce statement) its working fine. however when i try to use single line reduce statement, its not working. i understand its due to splice command in the reduce statement. can anyone advise how to overcome this type of scenario to write reduce statement in single line?

function order(words){
    // ...
    let regex = /\d+/g;
    let matches = words.match(regex)

    // return words.split(' ').reduce((finalar, element, indx) => {
    //     console.log('matches', matches);
    //     finalar.splice(matches[indx] - 1, 0, element)
    //     console.log('element', element);
    //     return finalar;
    // }, []).join(' ');
    return words.split(' ').reduce((finalar, element, indx) => finalar.splice([matches[indx] - 1],0,element) , []);
}

console.log(order("is2 Thi1s T4est 3a"));  //Output: Thi1s is2 3a T4est

Solution

  • You could map the splitted string with the values of matches as indices.

    function order(words) {
        const
            regex = /\d+/g,
            matches = words.match(regex);
    
        return words
            .split(' ')
            .map((_, i, a) => a[matches[i] - 1])
            .join(' ');
    }
    
    console.log(order("is2 Thi1s T4est 3a")); //Output: Thi1s is2 3a T4est