Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
how to delete element from array

I'm facing an issue to fix a bug.

I'm getting data from dataBase. the data ( object ) contains an array of names. I have useState hook that contains an array of objects. The value is names. I want to delete every object from the useState hook that much the name from the array fetched for dataBase.

Exp:

response.data.players = ["player1", "player2"]

const [names, setNames] = useState([
{value: "player1", label: "player1"},
{value: "player3", label: "player3"},
{value: "player2", label: "player2"},
{value: "player5", label: "player5"},
])

I want the names become like this:

[
{value: "player3", label: "player3"},
{value: "player5", label: "player5"},
]

with minimum time complexity ( I'm already using .map to serve other hook with the names, if I can use it it will be perfect for the time complexity )

Thank you

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

That just sounds like a filter to me. Can't you just do something like this:

setNames(names.filter(name => !response.data.players.includes(name.label)))

For reference, here's that working without React:

const names = [{
    value: "player1",
    label: "player1"
  },
  {
    value: "player3",
    label: "player3"
  },
  {
    value: "player2",
    label: "player2"
  },
  {
    value: "player5",
    label: "player5"
  },
];

const response = {
  data: {
    players: ["player1", "player2"],
  },
};


const filteredNames = names.filter(name => !response.data.players.includes(name.label))

console.log(filteredNames);

about 4 years ago · Juan Pablo Isaza Report

0

You can efficiently achieve the result using Set and filter

const names = [
  { value: "player1", label: "player1" },
  { value: "player3", label: "player3" },
  { value: "player2", label: "player2" },
  { value: "player5", label: "player5" },
];

const players = ["player1", "player2"];

const set = new Set(players);
const result = names.filter(({ label }) => !set.has(label));
console.log(result);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!