I'm working on simple list where you can simply add your words to the list. Main problem is duplicates, I tried many solutions but they weren't even close.
state = {
people: [{ name: null, count: null }]
}
handleSubmit = (e) => {
this.setState(({ count }) => ({
count: count + 1
}));
this.props.addHuman(this.state);
}
addHuman = (human) => {
let people = [...this.state.people, human];
this.setState({
people: people
});
}
I hope for solution which will check if there is any duplicate already in the array
I'm working on simple list where you can simply add your words to the list. Main problem is duplicates, I tried many solutions but they weren't even close.
state = {
people: [{ name: null, count: null }]
}
handleSubmit = (e) => {
this.setState(({ count }) => ({
count: count + 1
}));
this.props.addHuman(this.state);
}
addHuman = (human) => {
let people = [...this.state.people, human];
this.setState({
people: people
});
}
I hope for solution which will check if there is any duplicate already in the array
Share Improve this question asked Jul 31, 2020 at 17:38 FifcioFifcio 531 gold badge1 silver badge8 bronze badges 3- 1 What's the end goal ? To prevent adding duplicates ? Please add input and expected output. Is "count" your attempt at detecting duplicates or the actual data structure ? – nip Commented Jul 31, 2020 at 17:40
- 1 Does this answer your question? How to get distinct values from an array of objects in JavaScript? – Vasanth Gopal Commented Jul 31, 2020 at 17:45
- You forgot to mention what you consider a duplicate. – HMR Commented Jul 31, 2020 at 18:02
4 Answers
Reset to default 6You could make a check if there is someone with the same name already in the array. A better property to check would be an email adresse.
find
takes a callback function as parameter. Inside this function, I pare the name properties. If it's a match, find
returns true
, then a do an early return in the next line and the person isn't added.
addHuman = (human) => {
const exists = this.state.people.find(p => p.name === human.name);
if (exists) return;
let people = [...this.state.people, human];
this.setState({
people: people
});
}
https://developer.mozilla/de/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if you want to de duplicate the array...you can do it in this way
cont array = [1,1.2,3,5,5];
[...new Set(array)]
This will work as well, there are plenty of ways to achieve the desired oute.
addHuman = human => {
const updatedPeople = people.includes(human) ? people : [ ...people, human ];
this.setState({
people: updatedPeople
});
}
Remove_Duplicate_recs(filteredRecord)
{
var records = [];
for (let record of filteredRecord)
{
const duplicate_recorde_exists = records.find(r => r.MovementId ===
record.MovementId);
if (duplicate_recorde_exists)
{
continue ;
}
else
{
records.push(record);
}
}
return records;
}