Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

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)
       
   }
question from:https://stackoverflow.com/questions/65845246/is-there-a-solution-to-reorganize-the-following-array-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...