简体   繁体   中英

Reduce array of objects in javascript

I have an array of objects in javascript that i want to reduce. See code below. message with 6 or more digits is verified, fewer is unverified. I group them by group.

"

Use an array as the initial value of your accumulator and inside .reduce<\/code> , use findIndex<\/code> to check for the current group, if found, update verified<\/code> and unverified<\/code> values, otherwise, insert a new one :

You can simply extend your solution\/output to get the actual required output using Object.entries()<\/code> or Object.keys()<\/code> . I am going to use Object.entries()<\/code>

I couldn't resist refactoring your code a little. That said. what I have done:

  • <\/li>
  • <\/li>
  • <\/li><\/ul>

     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) => { if( acc.findIndex(e => e.group === line.group) === -1 ) { acc.push({ group: line.group, verified: 0, unverified: 0 }); } let group = acc.find(e => e.group === line.group); if( line.message.match(\/\\d{6,}\/) ) group.verified++; else group.unverified++; return acc; }, []); console.log(output);<\/code><\/pre>

    "

You can use map()<\/code> on Object.entries<\/code> . I also refactored your code in reduce<\/code> method

Put the group<\/code> prop in your acc. Then use Object.values<\/code> function to return the values of an object.

Use reduce in combination with regex testing like this -

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM