Home > Software engineering >  Use array find() method instead of for loop
Use array find() method instead of for loop

Time:03-11

How can we use Array.find() method instead of for loop in this code ?

onLoadTickets() {
    const ticketsReq = this.ticketService.getTickets();
    const tariffsReq = this.tariffService.getTariffs();

    forkJoin([ticketsReq, tariffsReq]).subscribe(results => {
      const data = results[0];
      const tariffResp = results[1];
      this.tickets = data.requests;
      for (let i = 0; i < this.tickets.length; i  ) {
        for (let j = 0; j < tariffResp.tariffs?.length; j  ) {
          if (tariffResp.tariffs[j].id == this.tickets[i].tariffId) {
            this.tickets[i].tariff = tariffResp.tariffs[j]
          }
        }
      }
    });
  }

Note :

Using find() method is not mandatory. I have to write this code with any array methods.

CodePudding user response:

this.tickets=data.request.map(x=>{
  const obj:any=x;
  obj.tariff=tariffResp.find(t=>t.id==x.tariffId)
  return obj
})

You loop over data.request using map. map transform an array in another

First you create an object with the values of x

After you add a new propety "tariff" that is the "tariffResp" who has the "id" property equal to the property "tariffId" of x

Check find and map methods of an array

CodePudding user response:

Array.find() method returns the first element in the provided array that satisfies the provided testing function.

So, if in your case you only have one tariff against all the tickets then you can go ahead with Array.find() but if you have multiple tariff and multiple tickets then you can go ahead with Array.filter().

Demo with Array.find() :

const tickets = [{
    tariffId: 1,
  name: 'Ticket 1'
}, {
    tariffId: 2,
  name: 'Ticket 2'
}];

const tariffResp = {
    tariffs: [{
    id: 1
  }]
};

const result = tickets.find((obj) => tariffResp.tariffs[0].id);

console.log(result);

Demo with Array.map() along with Array.filter() :

const tickets = [{
    tariffId: 1,
  name: 'Ticket 1'
}, {
    tariffId: 2,
  name: 'Ticket 2'
}, {
    tariffId: 3,
  name: 'Ticket 3'
}];

const tariffResp = {
    tariffs: [{
    id: 1
  }, {
    id: 2
  }]
};

const result = tariffResp.tariffs.map((obj) => {
    return tickets.filter((ticketObj) => obj.id === ticketObj.tariffId);
});

console.log(result);

  • Related