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
CodePudding user response:
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);
CodePudding user response:
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);