Search code examples
javascriptarraysecmascript-6arrow-functions

How to reduce an array from Right to Left?


How Can i reduce the array from Right to Left so that I get this output instead of the snippet?

[{
  "id": 134116,
  "user": "admin",
  "historyno": "134116-0"
}, {
  "id": 134132,
  "user": "admin",
  "historyno": "134132-0"
}, {
  "id": 134133,
  "user": "admin",
  "historyno": "134133-0"
}];

const input = [{"id":134116,"user":"admin","historyno":"134116-0"},{"id":134132,"user":"admin","historyno":"134132-0"},{"id":134132,"user":"admin","historyno":"134132-1"},{"id":134133,"user":"admin","historyno":"134133-0"},{"id":134133,"user":"admin","historyno":"134133-1"}];

const output = [...input.reduce((r, o) => r.set(o.id, o), new Map).values()];

console.log(output);

I got this code from an earlier post


Solution

  • Why not take Array#reduceRight?

    const
        input = [{ id: 134116, user: "admin", historyno: "134116-0" }, { id: 134132, user: "admin", historyno: "134132-0" }, { id: 134132, user: "admin", historyno: "134132-1" }, { id: 134133, user: "admin", historyno: "134133-0" }, { id: 134133, user: "admin", historyno: "134133-1" }],
        output = [...input.reduceRight((r, o) => r.set(o.id, o), new Map).values()];
    
    console.log(output);
    .as-console-wrapper { max-height: 100% !important; top: 0; }