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

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 ? 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? Commented Jul 31, 2020 at 17:45
  • You forgot to mention what you consider a duplicate. Commented Jul 31, 2020 at 18:02

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

Comments

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)]

Comments

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
 });
}

Comments

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;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.