0

The results I want to achieve are:

If the entered name is already on the array "persons", show an alert "Name already exist".

The code is not working, because I keep on getting the alert message all the time. I think the condition comparison variable (personObject.name ) is wrong.

Can someone explain how this should be done?

Without the condition, the names ad added propperly into the array.

//Condition
 if (persons.map((person) => person.name === personObject.name) )
 {
    alert("Name already exist");
   
 }
    else
    {
    
    //*/

    setPersons(persons.concat(personObject))
    setNewName('')
  console.log(persons) 
}

Code sandbox Full code:

const App = () => {
  //Reminder: current state, function that updates it, initial state.
  const [persons, setPersons] = useState([
    //The array persons is empty at start
  ]);
  const [newName, setNewName] = useState('');

  //adding new persons

  const addPerson = (event) => {
    event.preventDefault();
    /* complete the addPerson function for creating new persons */
    const personObject = {
      name: newName,

      id: persons.length + 1,
    };

    //Condition
    if (persons.map((person) => person.name === personObject.name)) {
      alert('Name already exist');
    } else {
      //*/

      setPersons(persons.concat(personObject));
      setNewName('');
      console.log(persons);
    }
  };

  const handlePersonChange = (event) => {
    console.log(event.target.value);
    setNewName(event.target.value);
  };

  return (
    <div>
      <h2>Phonebook</h2>

      <form onSubmit={addPerson}>
        <div>
          name:
          <input value={newName} onChange={handlePersonChange} />
        </div>
        <div>
          <button type="submit">add</button>
        </div>
      </form>
      <h2>Numbers</h2>

      {console.log(persons)}
      <ul>
        {persons.map((person) => (
          <li key={person.id}>{person.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Lahey Corey
  • 83
  • 1
  • 8
  • 1
    Does this answer your question? [Check if object value exists within a Javascript array of objects and if not add a new object to array](https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add) – adiga May 18 '21 at 11:04
  • Use [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) instead of `map` – adiga May 18 '21 at 11:04
  • `map` returns an array. An array is an object. An object is true. Did you mean to write `map(..).length`? – Martin May 18 '21 at 11:10

2 Answers2

2

You are checking condition with using map and map will return new array so if condition will be always true.

So instead of map you should use some like below:-

persons.some((person) => person.name === personObject.name);
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Priyank Kachhela
  • 2,517
  • 8
  • 16
0

You can use the filter method that filters an array and returns you an array with items matching the condition, if this new array is empty it means no items matches it :

let alreadyExists = persons.filter(person => person.name === personObject.name)

if (alreadyExists.length > 0) {
  alert("Name already exist")
} else {
  setPersons(persons.concat(personObject))
  setNewName('')
  console.log(persons) 
}
VersifiXion
  • 2,152
  • 5
  • 22
  • 40