0

I have an input that allows users to enter there name and a number, and this is displayed in a list. I am now trying to add these numbers into an array so I can stop duplicate ones from being added.

I think I'm close to a solution as I have the numbers being saved into my variable, however the issue I'm having is that only one number is being saved - and then gets overwritten whenever a new input value is entered. They should all get added into the same array.

Console log of Array after 3 input values are added

const [name, setName] = useState('');
  const [number, setNumber] = useState('');
  const [assigned, takenNumber] = useState([]);

  //
  // Handle adding players to the game
  function handleChange(event) {
    setName(event.target.value);
  }
  function handleNumber(event) {
    setNumber(event.target.value);
  }
  function handleAdd() {
    dispatchListData({ type: 'ADD_ITEM', name, number, id: uuidv4() });
    setName('');
    setNumber('');
    // Save all numbers in an array
    const numbersArray = [assigned];
    numbersArray.push(number);
    takenNumber(numbersArray);

    console.log(numbersArray);
  }

//
// Add players to game form
const AddItem = ({ number, name, onChange, onNumber, onAdd }) => (
  <form>
    <input type="text" value={name} onChange={handleChange} />
    <input type="number" value={number} onChange={handleNumber} min="1" max="20" />
    <button type="button" onClick={handleAdd}>
      Add
    </button>
  </form>
);
1
  • 2
    Is const numbersArray = [assigned]; meant to be const numbersArray = [...assigned];? Otherwise every update nests the existing data inside another array. Commented Dec 21, 2022 at 14:31

1 Answer 1

1

It looks like you're nesting your arrays there. assigned is an array, and you are creating numbersArray as an array containing this array.

const assigned = [1]
const numbersArray = [assigned];
// numbersArray is [[1]]

You should use the spread operator ... to spread the elements of assigned into your new array.

const numbersArray = [...assigned];

Here is the documentation for the spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

By the way, you should take a look into the Set structure. It looks like you could solve your problem using it, as it is basically an array that has no duplicates. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

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

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.