Home > front end >  JavaScript Add item to array if its not already exist
JavaScript Add item to array if its not already exist

Time:07-23

How can I check in JavaScript if the array already have the item? Im adding the items to my array with the next code:

    const booked_hours = [];
    for (let i = 0; i < apptid_set.size; i  ) {
        const book_hours = [...book_times][i].split(" ");
        booked_hours.push(book_hours[2]);
     }
     //alert(booked_hours);

Its works well, just in the booked_hours shouldnt be any duplicated item. How can I do that?

CodePudding user response:

You can use a set instead of an array for booked_hours

const booked_hours = new Set();
for (let i = 0; i < apptid_set.size; i  ) {
    const book_hours = book_times[i].split(' ');
    booked_hours.add(book_hours[2]);
}

And to convert it back to an array you can do [...booked_hours]

CodePudding user response:

Without knowing what you're adding to the booked_hours array this answer might have to be tweaked but take a look at this.

 const booked_hours = [];
    for (let i = 0; i < apptid_set.size; i  ) {
        const book_hours = [...book_times][i].split(" ");
        if (!booked_hours.includes(book_hours[2])) {
          booked_hours.push(book_hours[2]);
        }
     }
  • Related