Skip to content
Advertisement

How to take back more than one values from function in JavaScript

thanks in advance

am wondering how can i get many values from a code block..i dont know wiether i have to use array or anything…am new to js

consider the html code

 <div class="row">
            
            <div class=" available seat" data="C-08" ></div>
            <label>C-08</label>

            <div class=" available seat" data="D-08"></div>
            <label>D-08</label>

            <div class=" available seat" data="E-08"></div>
            <label >E-08</label>

            
        </div>

i need to get back seat numbers of each seats like……E08 FO8 ETC

What i did is

 let selectedSeats=document.querySelectorAll('.row .seat.available'); 
   let seatNumber=[]
   selectedSeats.forEach((sts)=>{
          seatNumbers=[sts.nextElementSibling.innerText];
     });
console.log(seatNumbers);

am getting only last seat number on log

anybody please tell me how can i get all the seat numbers

Advertisement

Answer

Use Array#Push to push text to your seatNumber array[].

Also instead of using nextElementSibling i would rec-emend using new data attributes which are much feasible and easy to use.

Using data attributes will ensure you are getting exact data you want from the div and not unwanted spaces or etc etc from the label

Edit: Since you highlighted that you want to only push unique value and avoid duplicates for that you can use IndexOf() to check if the array contains the existing seat number. It will only only the unique seat numbers only.

Live Demo:

let selectedSeats = document.querySelectorAll('.row .seat.available');
let seatNumber = []
selectedSeats.forEach((sts) => {
  let seats = sts.getAttribute('data') //get seat number
  if (seatNumber.indexOf(seats) === -1) {
    seatNumber.push(seats); //only push unique seats in to the array
  }
});
console.log(seatNumber);
<div class="row">

  <div class="available seat" data="C-08"></div>
  <label>C-08</label>

  <div class="available seat" data="A-02"></div>
  <label>A-02 - duplicate</label>

  <div class="available seat" data="D-08"></div>
  <label>D-08</label>

  <div class="available seat" data="A-02"></div>
  <label>A-02 - </label>

  <div class="available seat" data="E-08"></div>
  <label>E-08</label>

  <div class="available seat" data="E-08"></div>
  <label>E-08 duplicate</label>


</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement