Reputation: 81
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
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
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
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
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