I would like to know how to map an array, where the first result of the array has to be the one that meets the condition, but the rest continue to be mapped. For example, let the first result of the array be the Organizer and the rest be the Participants . The condition to filter by:
{assistant.id === ownerId ? "Organizador" : "Participante"}
This is my react component.
interface Props {
assistants: Assistant[];
ownerId: Id;
}
export const EventAssistants = ({ assistants, ownerId }: Props) => {
return (
<section>
<StyledSectionTitle>Asistentes ({assistants.length})</StyledSectionTitle>
<StyledAssitantsList>
{assistants.map((assistant) => (
<li key={assistant.id}>
<StyledAssistant>
<StyledFlex
flexDirection="column"
justifyContent="center"
alignItems="center"
>
<StyledUserImage background={assistant.avatar} size="70px" />
<p className="fullname">
{assistant.name} {`${assistant.lastName.substring(0, 1)}.`}
</p>
<p className="usertype">
{assistant.id === ownerId ? "Organizador" : "Participante"}
</p>
</StyledFlex>
</StyledAssistant>
</li>
))}
</StyledAssitantsList>
</section>
);
};
Any guidance or help would be great. Thank you very much!
If it has to be yes or yes with map() it dismisses this answer, otherwise this may help you:
It is a function to which I pass the array and check if position 0 has a true result, if so I do a for loop that starts counting from 1, since position 0 is the one verified and I put everything in a new array with the spread operator with which you have your original array intact (if you want you can overwrite the original.
Hello jaumeserr to move a certain index element that meets a condition, it would be as follows:
based on this post https://stackoverflow.com/questions/5306680/move-an-array-element-from-one-array-position-to-another
If you see there, first look for the position and then call the function and pass the arguments it asks for and that's it. Hope this can help you. Cheers
You can do that with a reduce
Participants are added to the array, but if the participant is the organizer, it is added to the beginning of the array, until they are all processed.
To map an array and filter by conditions I recommend using
filter
javascript where you map an array andfilter
it returns all the elements that meet the conditionIn the example above, it searches for all the elements
planCuidados
that meet the condition and saves them inplanEncontrado
In your case, it would be something like:Remember that you can complement filter with
find
,map
,reduce
, in addition you can also use more than one condition with filterI leave documentation about
filter
it in the following link: Documentation filter