Efficient way to use If statement for checking the value is not being used in Javascript or JQuery

Viewed 44

I have four textboxes say textbox1, textbox2, textbox3, textbox4 in my HTML doc on a button click for btn1 I want to make sure that all the values entered in all four textboxes are distinct & unique. For which I am using the if condition.

$("#btn1").on("click", function(){

    if($("#textbox1").val() === $("#textbox2").val() || 
       $("#textbox1").val() === $("#textbox3").val() ||
       $("#textbox1").val() === $("#textbox4").val() ||
       $("#textbox2").val() === $("#textbox3").val() || 
       $("#textbox2").val() === $("#textbox4").val() ||
       $("#textbox3").val() === $("#textbox4").val() ) 
    {  alert("Values are not unique please check them."); }

});

Is there any way shorter than this?

2 Answers

You can make a set with an array. The set removes dupes so if the length does not match, there was dupes.

function checkIfArrayIsUnique(myArray) {
  return myArray.length === new Set(myArray).size;
}

$("button").on("click", function () {
  var vals = $(".tb").map( function () { return this.value }).get()
  console.log(checkIfArrayIsUnique(vals))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" class="tb" />
<input type="text" class="tb" />
<input type="text" class="tb" />
<input type="text" class="tb" />

<button type="button">Check</button>

You may want to "normalize" the values if you are looking for unique text without case. Example "aaa" vs "AAA"....

The simplest way of checking the uniqueness.

  • On a button, click push all the values into an array
  • Check the duplicates in array Use Map
  • If duplicate count is greater than 0 its mean values are duplicated.

For example

let fruits = ['Apple', 'apple', 'AppLE', 'Orange', 'ORANGE'];
let duplicates = new Map(fruits.map(s => [s.toLowerCase(), s]));

console.log([...duplicates.values()]);

... is a spread operator read more

Related