1

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

Fifcio
  • 53
  • 1
  • 7
  • 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 Jul 31 '20 at 17:40
  • 1
    Does this answer your question? [How to get distinct values from an array of objects in JavaScript?](https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript) – Vasanth Gopal Jul 31 '20 at 17:45
  • You forgot to mention what you consider a duplicate. – HMR Jul 31 '20 at 18:02

4 Answers4

5

You 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 compare 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.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/find

JohMun
  • 426
  • 2
  • 7
0

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)]
Rohan Naik
  • 240
  • 2
  • 9
0

This will work as well, there are plenty of ways to achieve the desired outcome.

addHuman = human => {
 const updatedPeople = people.includes(human) ? people : [ ...people, human ];

 this.setState({
  people: updatedPeople
 });
}
Wiktor Bednarz
  • 701
  • 3
  • 7
0

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;

}