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

122
Views
Complex array needs to update and add new objects but only adds

So I will try to give as much information as possible but if you need more I can provide it.

I am making a website that has a dropdown which inside it has some options from an array, lets say there are 4 for this example A, B, C and D. Now this dropdown works great by returning the selection I have made to this function below.

//Array example 
letterArray = [
        {letter: "A"},
        {letter: "B"},
        {letter: "C"},
        {letter: "D"}
    ]

    function changeLetter(value){
        console.log(value.letter); // This returns whichever one I selected nicely so if i click A in the dropdown i get A back.
    }

Imagine I am building a word of 4 letters lets say "ABCD" to keep it simple, what I need to do is render 4 of my dropdowns. On page load I only render 1 because I do not know the length of the word the user wants to make. I have something like this to map them.

{numberOfLetters.map((_, index) => {
   return(
    <div key={index}
      <LetterSelection 
      onChange={changeLetter} /> //THIS IS MY DROPDOWN COMPONENT
    </div>
    )
})

I then have a button which increases the count of numberOfLetters to increase the array which makes the map longer. This all works fine still...

My attempt at getting this to work is like so, I change my function to have a state like this.

const [array, setArray] = useState([]);
function changeLetter(value){
   setArray(oldArray => [...oldArray, {option: value.letter}])
   console.log(array);
}

This pushes my selection to the array nicely and almost giving me what I want.

THE PROBLEM

If the user then decides to change the selection from say "A,B,C,D" to "A,C,B,D" another letter gets added to the array effectively becoming "A,B,C,D,C". I thought about using splice here to only get the 4 I want but it then misses out one of the user selected options(Not the correct one!).

So how do i get it so it updates the correct selection rather than adding a new object to the array?

Can post more code if needed.

about 4 years ago · Juan Pablo Isaza
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!