const Chat = () => {
const [array1, setArray1] = useState(['one', 'two', 'three', 'four', 'five']);
const [array2, setArray2] = useState(['four', 'two']);
return (
<div>
<ul>
{array1.map((d) => {
return array2.forEach((e) => {
return d === e ? <li>{e}</li> : '';
});
})}
</ul>
</div>
);
};
export default Chat;
I expect my list items to render in order:
-"two"
-"four"
My logic, I will go through array1 and if I find matches from array2, then output them to the renderer. However, nothing comes to the render at all. Tell me what am I doing wrong?
CodePudding user response:
The issue is that your for each method does not return anything, so you're really just returning an array of undefined. You can keep the same logic, even though it's a bit odd to set something in state that you won't mutate:
const Chat = () => {
const [array1, setArray1] = useState(["one", "two", "three", "four", "five"]);
const [array2, setArray2] = useState(["four", "two"]);
return (
<div>
<ul>
{array1.flatMap((d) => {
return array2.map((e) => {
return d === e ? <li>{e}</li> : "";
});
})}
</ul>
</div>
);
};
export default Chat;
Since you're returning an array of arrays technically, and flat map does the same logic and flattens the result.
CodePudding user response:
You can do:
const Chat = () => {
const [array1, setArray1] = useState(['one', 'two', 'three', 'four', 'five'])
const [array2, setArray2] = useState(['four', 'two'])
return (
<div>
<ul>
{array1
.filter((e) => array2.includes(e))
.map((e) => (
<li>{e}</li>
))}
</ul>
</div>
)
}
export default Chat