题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
主要用Object来解决该题 完整代码如下:
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); let lines = []; let res = []; rl.on("line", function (line) { lines.push(line); if (lines.length - 1 == parseInt(lines[0])) { lines.shift();//去掉第一个元素 let newLines = lines.map(x => x.split(' ').map(Number)) //split成新数组 let res = newLines.reduce((a, v) => ({ ...a, [v[0]]: v[1] + (a[v[0]] = a[v[0]] ? a[v[0]] : 0)}), {}); // reduce方法是关键,将array转化为Object for (const [key, value] of Object.entries(res)) { // 在Object中进行for循环 console.log(`${key} ${value}`); // 按照输出规则打印每个元素 } } });