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
415 views
in Technique[技术] by (71.8m points)

javascript - 合并JavaScript中对象数组的继续值(Combine continue values from array of objects in JavaScript)

My result should combine the consecutive tags, if tags are the same then I want to combine those text into a single one.

(我的结果应该合并连续的标签,如果标签相同,那么我想将那些文本合并为一个。)

So, from below input my output shoud be:

(因此,从下面输入我的输出应该是:)

Speaker-2:Do you want the systems in English or en espanol
Speaker-1:Heinous Spaniel
Speaker-2:For English press one for Spanish press 2 in Espanol
Speaker-1:Choirs a horror Janeiro at e ends in the pro gun to sober Tuesday to enter but I will have email but if you a new window
Speaker-2:but I put one that's 1 or 2.0 press he only those

 const note = [ { text: 'do you want the systems in English or en espanol', tag: 2, }, { text: 'heinous Spaniel', tag: 1, }, { text: ' for English press one for Spanish press 2', tag: 2, }, { text: ' in Espanol', tag: 2, }, { text: ' choirs a horror Janeiro at e ends in the pro gun to sober Tuesday to enter', tag: 1, }, { text: ' but I will have email but if you a new window', tag: 1, }, { text: " but I put one that's 1 or 2.0 press he only those", tag: 2, }, ]; const ip = note .map((e, i) => { const chanel = e.tag; let te = e.text.trim(); const next = note[i - 1] ? note[i - 1].tag : 0; if (chanel === next) { te = `${note[i - 1].text.trim()} ${te}`; note[i - 1].text = te; note.splice(i, 1); } return { [`Speaker-${chanel}`]: te.charAt(0).toUpperCase() + te.slice(1), }; }) .filter(e => !!e); let strimged = JSON.stringify(ip) .replace(/[{}"]/g, '') .split(',') .join('\n'); strimged = strimged.substring(1, strimged.length - 1); console.log(strimged); 

  ask by Nikhil Savaliya translate from so


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

1 Answer

0 votes
by (71.8m points)

Array.reduce() is your answer.

(Array.reduce()是您的答案。)

 const note = [ { text: 'do you want the systems in English or en espanol', tag: 2, }, { text: 'heinous Spaniel', tag: 1, }, { text: ' for English press one for Spanish press 2', tag: 2, }, { text: ' in Espanol', tag: 2, }, { text: ' choirs a horror Janeiro at e ends in the pro gun to sober Tuesday to enter', tag: 1, }, { text: ' but I will have email but if you a new window', tag: 1, }, { text: " but I put one that's 1 or 2.0 press he only those", tag: 2, }, ]; let previous = 0; let result = note.reduce((total, item) => { if(item.tag === previous) { total += item.text; } else { total += `\nSpeaker-${item.tag}: ` + item.text; previous = item.tag; } return total; }, ''); console.log(result); 


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

...