I have a project in React. In this Project, I have some array of users stored and I have one more array that contains message objects having three properties from, to, and message. Now I want, if the user id is not present message array then remove the user from the list. I am using Node.js as a backend. Or in simple words if the user has not sent or received any messages, then remove from them from the user list. Or if there any other solution for storing the users and messages in a single array.
users.json
[
{
"id": "1",
"name": "Rampal"
},
{
"id": "2",
"name": "Anisha"
},
{
"id": "3",
"name": "john"
}
]
messages.json
[
{
"from": 1,
"to": 2,
"message": "Please call me"
},
{
"from": 3,
"to": 2,
"message": "Please call me"
}
]
Showusers.js
import React, { useEffect, useState } from "react";
import axios from "axios";
import ShowSingle from "./ShowSingle";
import ShowRecentSingle from "./ShowRecentSingle";
function Showusers() {
const [users, setUsers] = useState();
const [loading, setLoading] = useState(true);
useEffect(() => {
axios
.get("http://localhost:3005/")
.then(function (response) {
setUsers(response.data);
console.log("users" + JSON.stringify(response.data));
setLoading(false);
})
.catch(function (error) {
console.log(error);
setLoading(false);
});
}, []);
return (
<div>
{!loading &&
users.map((user, id) => <ShowRecentSingle key={id} user={user} />)}
<input
type="text"
name="message"
id=""
className="message-input"
placeholder="type new message....."
/>
</div>
);
}
export default Showusers;
let users = [
{
"id": "1",
"name": "Rampal"
},
{
"id": "2",
"name": "Anisha"
},
{
"id": "3",
"name": "john"
}
];
let messages = [
{
"from": 1,
"to": 2,
"message": "Please call me"
},
{
"from": 3,
"to": 2,
"message": "Please call me"
}
];
let res = users.map(x => Object.assign(x, messages.find(y => y.from == x.id)));
for (let i = 0; i < res.length; i++) {
if(res[i].from === undefined) {
res.splice(i, 1);
}
}
console.log(res)
You can maintain a map of active users who either send or receive messages and then filter out inactive users from the array of users with it.
const usersArray = [
{
id: 1,
name: "Rampal"
},
{
id: 2,
name: "Anisha"
},
{
id: 3,
name: "john"
}
];
const messagesArrary = [
{
from: 1,
to: 2,
message: "Please call me"
},
{
from: 3,
to: 2,
message: "Please call me"
}
];
const getActiveUserProfiles = (messages) => {
// map of users who sent or receive messages
const activeUsers = new Map();
messages.forEach(({ to, from }) => {
activeUsers.set(to, to);
activeUsers.set(from, from);
});
// filter out inactive users
return usersArray.filter(({ id }) => activeUsers.get(id));
};
const activeUserProfiles = getActiveUserProfiles(messagesArrary);
console.log(activeUserProfiles);