DEV Community

Aaron
Aaron

Posted on • Edited on

10 5

Three ways to use reduce in javascript

In this video we explore the reduce method and demonstrate three different use cases you can use in your next JavaScript project.

Data used

export const eg1 = [1, 45, 2, 3, 34, 4];
export const eg2 = [
  {
    gender: "male",
    name: "Ed"
  },
  {
    gender: "male",
    name: "Bob"
  },
  {
    gender: "female",
    name: "Sarah"
  }
];
export const eg3 = [
  1,45,2,3,34,4,1,2,
  3,4,5,6,3,2,9
];

1 - sum all items in array

const one = eg1.reduce(
  (prev, current) => prev + current,0
);
console.log(one);
//outputs 189

2 - group items by type

const two = eg2.reduce(
  (obj, item) => ({
    ...obj,
    [item['gender']]: [
      /** check if exists
       * if it doesn't start with blank array
       */
      ...obj[item['gender']] || [],
      item
    ]
  }),
  {} //default value
);
console.log(two)
//outputs {male: Array[2], female: Array[1]}

3 - count how many times item in array

const three = eg3.reduce(
  (tally, item) => ({
    ...tally,
    [item]: (tally[item] || 0) + 1
  }),
  {}
);
console.log(three);
//outputs Object {1: 2, 2: 3, 3: 3, 4: 2, 5: 1…}

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (8)

Collapse
 
itsrauf profile image
Rauf Islam

I'd really appreciate it if you would show the original arrays in the snippets

Collapse
 
afewminutesofcode profile image
Aaron

Thanks so much for the suggestion I have updated the post. Have a great day

Collapse
 
mati365 profile image
Mateusz Bagiński • Edited

All of these examples sucks. Why do you copy object every accumulator assign? It is slow and it has bigger complexity than mutable assign

Collapse
 
aronhoyer profile image
Aron Høyer

Dude calm down. Try to be a bit more constructive. Instead of pointing out people’s mistakes, show how it could be improved and why it’s an improvement. Just telling someone they suck, isn’t helpful, and can impact their self confidence in a bad way. Everyone just does their best with the knowledge they have. Please remember that.

Collapse
 
rolandcsibrei profile image
Roland Csibrei

Sadly, I must agree with Mateusz. Just DO NOT post shitty examples when you are not enough experienced to do so. The quality of this site went shit because of low quality articles written by noobs. Someone should check them prior publishing. No offense dude however. Have a great day!

Thread Thread
 
thesinding profile image
Simon Sinding

Friendly community here, that's great!

Thread Thread
 
afewminutesofcode profile image
Aaron

Thanks for the support here Aron and Simon, I am enjoying helping many people starting out with web development and the dev.to community has been awesome!

I strive to create working examples and snippets for beginners and am happy for more experienced developers to join in the conversation and suggest improvements.

I am not going to let the negative feedback stop me from continuing to help out other developers, I just hope they don't treat other developers like this in their workplace as I agree it could shatter the confidence of someone in their team to hear this kind of feedback.

Roalnd / Mateusz I will be happy to update my article with a link to your follow up article if you want to contribute to the community and post a better solution here.

Collapse
 
rolandcsibrei profile image
Roland Csibrei

Exactly, noobs posting bullshit everywhere... We are doomed! lol

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️