Skip to content
Advertisement

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?

Advertisement

Answer

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, do filter and get relevant pieces of 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)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement