Search code examples
javascriptarraysreduce

How to get array elements based on conditions using javascript array reduce?


So I have an array

const records = [
{
    value: 24,
    gender: "BOYS"
},
{
    value: 42,
    gender: "BOYS"
},
{
    value: 85,
    gender: "GIRLS"
},
{
    value: 12,
    gender: "GIRLS"
},
{
    value: 10,
    gender: "BOYS"
}

]

And I want to get only "Boys" objects within an array using js reduce() rather than filter(). Please help.


Solution

  • Уou can use any option you want

    const records = [{value: 24,gender: "BOYS"},{value: 42,gender: "BOYS"},{value: 85,gender: "GIRLS"},{value: 12,gender: "GIRLS"},{value: 10,gender: "BOYS"}]
    
    const withReduce = records.reduce((acc, item) => item.gender === "BOYS" ? [...acc, item] : acc, []);
    const withFlatMap = records.flatMap(item => item.gender === "BOYS" ? item : []);
    const withFilter = records.filter(({ gender }) => gender === "BOYS");
    
    console.log(withReduce);
    console.log(withFlatMap);
    console.log(withFilter);
    .as-console-wrapper { max-height: 100% !important; top: 0 }