Reputation: 37
I want to render a list of flight stops location codes.I have an array of my stops objects:
flight = {
departStops:1,
departSegments:{
{
departure: {iataCode: "TXL"},
arrival: {iataCode: "FRA"}
},
{
departure: {iataCode: "FRA"},
arrival: {iataCode: "YUL"}
}
}
inside my component function before the return I created the string constant:
const myString = flight.departSegments.reduce((acc,item) => {
if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
if (acc.length > 0) {
acc.concat(',',item.arrival.iataCode)
} else {
acc.concat(item.arrival.iataCode)
}
}
return acc
},"")
and this is how I render my string inside the component:
<div>
{
flight.departStops > 0
?
myString
:
null
}
</div>
the problem is that myString remains an empty string on rendering
Upvotes: 0
Views: 563
Reputation: 501
Strings are immutable in javascript in order to make it work you need to return acc.concat() result
const flight = {
departStops: 1,
departSegments: [
{
departure: { iataCode: 'TXL' },
arrival: { iataCode: 'FRA' }
},
{
departure: { iataCode: 'FRA' },
arrival: { iataCode: 'YUL' }
}
]
}
const myString = flight.departSegments.reduce((acc, item) => {
if (
item.arrival.iataCode !==
flight.departSegments[flight.departSegments.length - 1].arrival.iataCode
) {
if (acc.length > 0) {
return acc.concat(',', item.arrival.iataCode)
} else {
return acc.concat(item.arrival.iataCode)
}
}
return acc
}, '')
console.log(myString)
P.S.
You may simplify your render
<div> { (flight.departStops > 0) && myString } </div>
Upvotes: 1
Reputation: 4394
You need to return from reduce like this
if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
if (acc.length > 0) {
return acc.concat(',',item.arrival.iataCode)
} else {
return acc.concat(item.arrival.iataCode)
}
}
Also, the way you constructed departSegments is bad. It should be array, and not object.
Upvotes: 1