Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda