Micheal
Micheal

Reputation: 81

replace filter and map with reduce es6

I'm trying to avoid chaining with filter and map, but why my reduce returned undefined?

const data = [{
        value: "moto",
        passed: true
    },{
        value: "boat",
        passed: false
    }, {
        value: "car",
        passed: true
    }]

    // expected ['moto', 'car']
    // using filter and map
    data.filter(obj => obj.passed).map(obj => obj.value)

What's wrong? data.reduce((accum, obj) => obj.checked && [...accum, obj.value], [])

Upvotes: 5

Views: 5530

Answers (4)

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You can do:

const data = [{value: "moto",passed: true}, {value: "boat",passed: false}, {value: "car",passed: true}];
const result = data.reduce((a, { passed: p, value: v}) => p ? (a.push(v), a) : a, []);

console.log(result);

Upvotes: 4

Rushal Barkhade
Rushal Barkhade

Reputation: 1

const list =[
  {
    name:'Raj'
    ,
    age:40
  },{
    name:'Raj 2'
    ,
    age:20
  },{
    name:'Raj 3'
    ,
    age:30
  },{
    name:'Raj 4'
    ,
    age:20
  }]
  
  const result = list.reduce((a, c) => c.age>25 ? (a.push(c.name), a) : a, []);
  console.log(result)

Upvotes: 0

Nitish Narang
Nitish Narang

Reputation: 4184

It's because you are not returning anything if obj.passed = false. Updated below. Pls check

const data = [{
        value: "moto",
        passed: true
    },{
        value: "boat",
        passed: false
    }, {
        value: "car",
        passed: true
    }]

console.log(data.reduce((accum, obj) => 
              obj.passed 
                ? accum.concat(obj.value) 
                : accum
           , []))

Upvotes: 0

philipp
philipp

Reputation: 16495

 (accum, obj) => obj.checked && [...accum, obj.value]

does not return the filtered list, in case the object is not checked.

(accum, obj) => {
  if (obj.checked) accum.push(obj.value)
  return accum;
}

as reducer function will do that.

or to keep it as a oneliner, to not maintain readability:

(accum, obj) => obj.checked ? [...accum, obj.value] : accum;

Upvotes: 2

Related Questions