Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to replace map and filter with reduce in Javascript

I have this piece of code:

this.serverlist = data.NodeList.map((a) => {
  if (a.productTypeId === "1") {
    return a.HostName;
  }
});

this.serverlist = this.serverlist.filter((x) => {
  return x !== undefined;
});

And I want to replace this 2 statements(.map & .filter) with .reduce. How do I do that?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

 const NodeList = [ { productTypeId: "1", HostName: "abc.com" }, { productTypeId: "2", HostName: "abc.com" }, { productTypeId: "1" }, { productTypeId: "1", HostName: "xyz.com" }, ]; let serverlist = NodeList.reduce(a=> { if (a.productTypeId === "1", return x !== undefined) { return a.HostName }); console.log(serverlist );
about 4 years ago · Juan Pablo Isaza Report

0

I could understand your snippet as

 const NodeList = [ { productTypeId: "1", HostName: "abc.com" }, { productTypeId: "2", HostName: "abc.com" }, { productTypeId: "1" }, { productTypeId: "1", HostName: "xyz.com" }, ]; let serverlist = NodeList.map(a => { if (a.productTypeId === "1") { return a.HostName } }) serverlist = serverlist.filter(x => { return x !== undefined }) console.log(serverlist) // [ 'abc.com', 'xyz.com' ]

So you could combine to use reduce like this, filter and get relevant data in one go

 const NodeList = [ { productTypeId: "1", HostName: "abc.com" }, { productTypeId: "2", HostName: "abc.com" }, { productTypeId: "1" }, { productTypeId: "1", HostName: "xyz.com" }, ]; const serverlist = NodeList.reduce((acc, el) => { if (el.productTypeId === "1" && el.HostName) acc.push(el.HostName); return acc; }, []); console.log(serverlist);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!