Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use multiple Array.filter at once

I am trying to apply multiple array.filter at once in a single line, What it doesn’t return anything.

let data = [
{
  "name" : "Person1",
  "details":[
    {"status":"A"},
    {"status":"A"},
    {"status":"P"},
    {"status":"A"},
    {"status":"P"}
  ]
},{
  "name" : "Person2",
  "details":[
    {"status":"A"},
    {"status":"A"},
    {"status":"P"},
    {"status":"A"},
    {"status":"P"}
  ]
},{
  "name" : "Person3",
  "details":[
    {"status":"A"},
    {"status":"A"},
    {"status":"P"},
    {"status":"A"},
    {"status":"P"}
  ]
},{
  "name" : "Person4",
  "details":[
    {"status":"A"},
    {"status":"A"},
    {"status":"P"},
    {"status":"A"},
    {"status":"P"}
  ]
}
]

I am trying to collect all the A and P data and push into a single array for further next work.

My array.filter code is here:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var findA = data.filter(Obj=>Obj.details(InnerObj=>InnerObj.status === 'A'))

Am I using it correct because I am not getting anything

Result I want :

[
{
  "name" : "Person1",
  "A" : [
    {"status":"A"},
    {"status":"A"},
    {"status":"A"}
  ],
  "P":[
    {"status":"P"},
    {"status":"P"}
  ]
},{
  "name" : "Person2",
  "A" : [
    {"status":"A"},
    {"status":"A"},
    {"status":"A"}
  ],
  "P":[
    {"status":"P"},
    {"status":"P"}
  ]
}
]

>Solution :

You could map the outer objects and group details.

const
    data = [{ name: "Person1", details: [{ status: "A" }, { status: "A" }, { status: "P" }, { status: "A" }, { status: "P" }] }, { name: "Person2", details: [{ status: "A" }, { status: "A" }, { status: "P" }, { status: "A" }, { status: "P" }] }, { name: "Person3", details: [{ status: "A" }, { status: "A" }, { status: "P" }, { status: "A" }, { status: "P" }] }, { name: "Person4", details: [{ status: "A" }, { status: "A" }, { status: "P" }, { status: "A" }, { status: "P" }] }],
    result = data.map(({ name, details }) => ({ name, ...details.reduce((r, o) => {
        (r[o.status] ??= []).push(o);
        return r;
    }, {}) }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading