DEV Community

Diegoper
Diegoper

Posted on

3 2

How to Reduce Functions in Javascript

Run a list of functions and get a list of results:

Hi, I'm a new programmer!

I've been studying for a few months and would like to share this piece of code that came to mind when I studied about the Reduce() function.

I know it's something simple, but it could be useful for many people to extend it, comment on it and improve it.

// Run with Node 11 or higher // DATA-COLLECTING FUNCTIONS const func1 = () => { return { user: 'Diego Perdomo' } } const func2 = () => { return { skills: ['Js', 'React', 'Node', 'Sql'] } } const func3 = () => { return { webs: ['dpercode.com', 'dev.to/diegoper'] } } const func4 = () => { return { articles: ['My Article 1', 'My Article 2'] } } // CREATE ARRAY OF FUNCTIONS const myFunctions = [func1, func2, func3, func4] // REDUCE THE FUNCTIONS const funcReducer = myFunctions.reduce((funcAccumulator, nextFunc) => { let arrayFunc = []; funcAccumulator === undefined ? arrayFunc.push(nextFunc()) : arrayFunc.push(funcAccumulator, nextFunc()) return arrayFunc.flat(); }, undefined) // RESULTS console.log(funcReducer)
// RESULT
[
  { user: 'Diego Perdomo' },
  { skills: [ 'Js', 'React', 'Node', 'Sql' ] },
  { webs: [ 'dpercode.com', 'dev.to/diegoper' ] },
  { articles: [ 'My Article 1', 'My Article 2' ] }
]

Thanks for visiting my article...

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (2)

Collapse
 
savagepixie profile image
SavagePixie

Hey Diegoper. That's an interesting approach. However, I think that a map would be more appropriate in this case:

const result = myFunctions.map(func => func())
Collapse
 
diegoper profile image
Diegoper

Hahaha it's good... Thanks

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay