peterHasemann
peterHasemann

Reputation: 1590

JavaScript check for duplicate inputs in array and at least one letter

when I click on a button, I want to create an entry. This entry got a title and a text. Before I create the new entry, there should be checked, if this title already exists and if this title is empty. The check for empty is important because the text may not be " " (whitespace), this should have at least a digit / letter or number.

So this is what I got so far:

   var entries = store.getEntries(); // the entry list. Each entry has the property "title"

    function checkTitleInput(inputText) { // check the titleInput before creating a new entry

      if (inputText.length > 0 && // field is empty?
        /* at least 1 letter */ && // not just a whitespace in it?
        /* no duplicate */ // no duplicate in the entry list?
      )
        return true;

      return false;
    }

Could someone help me out here?

Upvotes: 0

Views: 46

Answers (2)

PeterMader
PeterMader

Reputation: 7285

Use Array#some and trim:

function checkTitleInput (inputText) {
  var trimmed = inputText.trim();
  var exists = entries.some((entry) => entry.title === trimmed);
  return trimmed.length > 0 && !exists;
}

You could make it even shorter:

function checkTitleInput (inputText) {
  var trimmed = inputText.trim();
  return !!trimmed && !entries.some((entry) => entry.title === trimmed);
}

Upvotes: 2

Jaydip Jadhav
Jaydip Jadhav

Reputation: 12309

I would modify this function as

function checkTitleInput(inputText) { 
 inputText   = inputText.trim();
 if (inputText.length > 0 && entries.filter(entry=>entry.title.equals(inputText)).length==0)
      return true;
 return false;
}

Upvotes: 2

Related Questions