[SOLVED] Check string elements in an array to manipulate


I have the following array returning from a service

indexLabelServices = [ ' Pear', ' Apple', ' Banana',' Peach',' Orange',' Cherry' ]

For each element of the array i want to give a different label ( translation )

This is my code

  const convertServicesLabels = (indexLabelServices) => {
    let label="";
    for (let index = 0; index < indexLabelServices.length; ++index) {
      const element = indexLabelServices[index];
      if(element === " Pear){
      }else  if(element ===" Apple"){
      }else  if(element ===" Banana"){
      }else  if(element ===" Peach"){
      }else  if(element ===" Orange"){
      }else  if(element ===" Cherry"){
    return label;

The result i have with this method is that the only the element Orange is translated to Arancia, not others element get transalated.

What am i doing wrong? How can i manipulate/translate any element of the array indexLabelServices ?


The problem is located within a for loop where you every iteration rewrite variable label. Another problem is iterating over that array. When you do ++index then variable index increment before enter the for loop body so instead try to use index++. In this case will be index increment after one iteration of for loop.

If you need to return array of all translation edit your code to something like this:

  let indexLabelServices = [ ' Pear', ' Apple', ' Banana',' Peach',' Orange',' Cherry' ];
  const convertServicesLabels = (indexLabelServices) => {
    let translations = [];
    for (let index = 0; index < indexLabelServices.length; index++) {
      const element = indexLabelServices[index];
      if(element === " Pear"){
          translations[index] = 'Pera';
      else if(element ===" Apple"){
          translations[index] = 'Mela';
      else if(element ===" Banana"){
         translations[index] = 'Platano';
      else if(element ===" Peach"){
          translations[index] = 'Pesca';
      else if(element ===" Orange"){
          translations[index] = 'Arancia';
      else if(element ===" Cherry"){
          translations[index] = 'Ciliegia';
    return translations;

Answered By – VojtÄ›ch Váchal

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *