3

I want to push a unique value in an array and I'm using jquery

var otNotesTimeIntrArray = new Array();
$("#otNoteFluids").on('change',function() {
   var otNotesTimeIntr = $("#otNotesTimeIntr").val();
   otNotesTimeIntrArray.push(otNotesTimeIntr);
 });

otNotesTimeIntr consists of Time intervals. Example: 10:15AM, 10:45AM...

If 10:15AM already exist, I don't want it to push into array..

2 Answers 2

5

Use can use .indexOf to check whether a value already exists in an array or not

var otNotesTimeIntrArray = new Array();
$("#otNoteFluids").on('change',function() {
   var otNotesTimeIntr = $("#otNotesTimeIntr").val();

   //Use .indexOf before pusing into array
   if(otNotesTimeIntrArray.indexOf(otNotesTimeIntr)==-1)
      otNotesTimeIntrArray.push(otNotesTimeIntr);

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

Comments

3

You can use array#includes to check if a value exists in an array.

var otNotesTimeIntrArray = new Array();
$("#otNoteFluids").on('change',function() {
   var otNotesTimeIntr = $("#otNotesTimeIntr").val();
   if(!otNotesTimeIntrArray.includes(otNotesTimeIntr))
     otNotesTimeIntrArray.push(otNotesTimeIntr);
 });

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.