Home > Software design >  How to get array elements based on conditions using javascript array reduce?
How to get array elements based on conditions using javascript array reduce?

Time:08-24

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.

CodePudding user response:

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

]

let boys = records.reduce((t,o)=>{
  if(o.gender === "BOYS") t.push(o)
  return t
},[])
console.log(boys)

CodePudding user response:

У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 }

  • Related