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

183
Views
Can I update an array of objects by modifiying a value return by array.find()?

I want to modify an object in an array by calling array.find() and then mutate the returned reference to indirectly mutate the array but that doesnt appear to work. I assumed from reading other articles that array.find() returns a reference to an object in the array on a successful match but that appears not the be the case.

In this codesandbox if I mutate the result from array.find() the array is not updated. I can update the array if I replace array.find() with array.findIndex() and modify the array elements by index, but the code is not as clean and I still dont understand why I cant update by reference.

Does array.find() return a reference to an object in the array or a copy? In the codesandbox provided it appears to behave as though its a copy.

Any advice is appreciated.

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

0

Find just finds the first element in the array, they do not edit the element, but find the element. So when you have the element, you can edit afterward, but you do not have the index of the element inside the array, so you will need the index too if you want to pass the edited element in the array.

You have multiple ways to update. If you want a shorter way, right now it came into my mind like this :

   setArray((oldState) =>
      oldState.map((item) => {
        if (item.value === "one") {
          return {
            value: "asdasd"
          };
        }
        return {...item};
      })
    );

So directly you can set the value inside setArray why? because the map returns a new array. Or you can write more readable :

 const newState = array.map((item) => {
        if (item.value === "one") {
          return {
            value: "asdasd"
          };
        }
        return {...item};
      });
    setArray(newState)

A similar question can be found here

If you have any questions ask. Thanks.

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!