减少Java脚本中的对象数组
我有一个想要减少的Java脚本对象数组。请参阅下面的代码。 6位或更多数字的消息已验证,未验证的消息较少。我把它们按组分组。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">const myArray = [
{ group: 'groupA', message: 'Text without a number', sl: '1A' },
{ group: 'groupA', message: 'Text with a number WO5467829', sl: '1A' },
{ group: 'groupB', message: 'Text without a number', sl: '1A' },
{ group: 'groupA', message: 'Text with a number WO5467829', sl: '1A' },
{ group: 'groupB', message: 'Text with a number WO5467829', sl: '1A' },
{ group: 'groupC', message: 'Text without a number', sl: '1B' },
{ group: 'groupD', message: 'Text with a number Tick0127866', sl: '1B' },
{ group: 'groupC', message: 'Text without a number', sl: '1A' }
];
output = myArray.reduce((acc, line) => {
let yes = 0;
let no = 0;
line.message.match(/d{6,}/) ? yes++ : no++;
acc[line.group] = acc[line.group] || {};
acc[line.group].verified = (acc[line.group].verified || 0) + yes;
acc[line.group].unverified = (acc[line.group].unverified || 0) + no;
return acc;
}, {});
console.log('output', output);
但是,我希望输出也是一个对象数组,如下所示:
[
{ group: 'groupA', verified: 2, unverified: 1 },
{ group: 'groupB', verified: 1, unverified: 1 },
{ group: 'groupC', verified: 0, unverified: 2 },
{ group: 'groupD', verified: 1, unverified: 0 }
]
我将如何执行此操作?
解决方案
使用数组作为累加器的初始值,在.reduce
中,使用findIndex
检查当前组,如果找到,则更新verified
和unverified
值,否则插入新的值:
const myArray = [
{ group: "groupA", message: "Text without a number", sl: "1A" },
{ group: "groupA", message: "Text with a number WO5467829", sl: "1A" },
{ group: "groupB", message: "Text without a number", sl: "1A" },
{ group: "groupA", message: "Text with a number WO5467829", sl: "1A" },
{ group: "groupB", message: "Text with a number WO5467829", sl: "1A" },
{ group: "groupC", message: "Text without a number", sl: "1B" },
{ group: "groupD", message: "Text with a number Tick0127866", sl: "1B" },
{ group: "groupC", message: "Text without a number", sl: "1A" }
];
output = myArray.reduce((acc, line) => {
let yes = 0;
let no = 0;
line.message.match(/d{6,}/) ? yes++ : no++;
// check if you have the group in the accumulator
const ndx = acc.findIndex(e => e.group === line.group);
// if you have it, manipulate verified and unverified
if (ndx > -1) {
acc[ndx].verified = (acc[ndx].verified || 0) + yes;
acc[ndx].unverified = (acc[ndx].unverified || 0) + no;
} else {
// insert a new entry instead
acc.push({
group: line.group,
verified: yes,
unverified: no
});
}
return acc;
}, []); // use an array as the initial value of the accumulator
console.log(output);
相关文章