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

213
Views
Only push the object which is not in the array yet

This is my function:

const multiSelect = value => {
    let tmpArr = [...selectedPeople];

    if (tmpArr.length === 0) {
      tmpArr.push(value);
    } else {
      tmpArr.map(item => {
        if (item.id !== value.id) {
          tmpArr.push(value);
        } else {
          return;
        }
      });
    }
    setSelectedPeople(tmpArr);
  };

I want to check the array for the new value by comparing it with all items. If value === item item the loop function should return, but if the value is not in the array yet, it should push it.

This is a big problem for me but I assume it is a small problem for you guys.

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

0

Use Array.every() to check if the array doesn't contain an item with the same id:

const multiSelect = value => {
  const tmpArr = [...selectedPeople];
  
  if(tmpArr.every(item => item.id !== value.id)) {
    tmpArr.push(value);
  }

  setSelectedPeople(tmpArr);
};

However, this means that you're duplicating the array needlessly, while causing a re-render, that won't do a thing. So check if the item is already a part of selectedPeople by using Array.some(), and if it does use return to exit the function early. If it's not continue with cloning, and updating the state:

const multiSelect = value => {
  if(tmpArr.some(item => item.id === value.id)) {
    return;
  }

  const tmpArr = [...selectedPeople];
  
  tmpArr.push(value);

  setSelectedPeople(tmpArr);
};
about 4 years ago · Juan Pablo Isaza Report

0

Use find to check if the item is already in the array. Also, there's no need to make a copy of the source array:

const multiSelect = value => {
    if (!selectedPeople.find(item => item.id === value.id))
        setSelectedPeople(selectedPeople.concat(value))
}
about 4 years ago · Juan Pablo Isaza Report

0

Another approach.

const
    multiSelect = value => setSelectedPeople([
        ...selectedPeople,
        ...selectedPeople.some(({ id }) => id === value.id)
            ? []
            : [value]
    ]);
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!