Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
Remove an object from an array of if not Present in Array

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;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Solution with Map

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);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda