Reputation: 47
Lets say I want to map an array of persons onto React components of the type person and want to also add a different field based on the previous object's values, usually you could do this if not comparing the values of current and previous object:
const PersonsMonth = ({persons}) => {
const personsList = persons.map((person)=> <Person key={person.Id} person={person}/>)
return(<>
<h3>Group members</h3>
{personsList}
</>
)
}
But what do I do if I want to say add a div when current person's height value is lower or higher than previous person's height. For example this pseudocode
if(currentperson.height>formerperson.height)
<div className="taller">!</div> in front of <Person key={person.Id} person={person}/>
if(currentperson.height<formerperson.height)
<div className="shorter">!</div> in front of <Person key={person.Id} person={person}/>
Upvotes: 2
Views: 4213
Reputation: 1
I think you can sort persons before map in react component
const persons = [
{
id:0,
name:'user1',
height:175,
},
{
id:1,
name:'user2',
height:183,
},
{
id:2,
name:'user3',
height:168,
}
]
const sortPersons = (persons) => {
function compare( a, b ) {
if ( a.height < b.height ){
return -1;
}
if ( a.height > b.height ){
return 1;
}
return 0;
}
return persons.sort( compare );
}
const PersonsMonth = () => {
const personsList = sortPersons(persons).map((person)=> <p key={person.id} >{person.height}</p>)
return(
<>
<h3>Group members</h3>
{personsList}
</>
)
}
Upvotes: 0
Reputation: 203218
You can use the additional arguments passed to the map callback, the index and array being iterated over, to access the previous element in the array. Use the Optional Chaining operator (?.
) to handle the edge case of mapping the first person in the array since they'll have no previous person before them in the array.
const PersonsMonth = ({ persons }) => {
const personsList = persons.map((person, index, arr)=> {
const prevPerson = arr[index - 1];
if (prevPerson?.height && person.height > prevPerson.height) {
return (
<Fragment key={person.id}>
<div className="taller">!</div> in front of <Person person={person}/>
</Fragment>
);
} else if (prevPerson?.height && person.height > prevPerson.height) {
return (
<Fragment key={person.id}>
<div className="shorter">!</div> in front of <Person person={person}/>
</Fragment>
);
}
return (
<Person key={person.Id} person={person}/>
);
});
return (
<>
<h3>Group members</h3>
{personsList}
</>
);
}
This could probably be made to be a little bit tighter code, more DRY.
const PersonsMonth = ({ persons }) => {
const personsList = persons.map((person, index, arr)=> {
const prevPerson = arr[index - 1];
return (
<Fragment key={person.id}>
{prevPerson?.height && person.height !== prevPerson.height && (
<>
<div className={person.height > prevPerson?.height ? "taller" : "shorter">!</div> in front of
</>
)}
<Person person={person}/>
</Fragment>
);
});
return (
<>
<h3>Group members</h3>
{personsList}
</>
);
}
Upvotes: 1