Skip to content
Advertisement

Is there a solution to reorganize the following array in javascript?

I want to transform this array ['1','3','+','8','0','/','5','7','0'] into ['13','+','80','/','570']

I tried this:

    let valu = val.value;
    let tab1 = [];
   
   if(!isNaN(valu)) {
       
        tab1.push(valu)   
    }

   else {
       
        tab.push(tab1)
        tab1 = [];
        tab.push(valu)
       
   }

Advertisement

Answer

You could test if the avtual value has only digits and if the last stored valu has digits, then add the avual value. Otherwise push the value to the result set.

const
    hasDigits = c => /^d+$/.test(c),
    array = ['1', '3', '+', '8', '0', '/', '5', '7', '0'],
    result = array.reduce((r, v) => {
        if (hasDigits(v) && hasDigits(r[r.length - 1] || '')) r[r.length - 1] += v;
        else r.push(v);
        return r;
    }, []);

console.log(result);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement