'Error mapbox layer only show the last conditional result

when i tried to add 2 layer like below, for ex: data[banana,chicken,banana,chicken,chicken]

for(let indexin data){ 
  if(data[index]=="banana"){
    map.addLayer({
      'id': 'router' + index,
      'type': 'line',
      'source': 'LineString' + index,
      'layout': {
          'line-join': 'round',
          'line-cap': 'round',
      },
      'paint': {
          'line-color': '#00FF00',
          'line-width': 4,
          'line-dasharray': [2, 4]
      }
   });
  } else{ 
    map.addLayer({
      'id': 'router' + index,
      'type': 'line',
      'source': 'LineString' + index,
      'layout': {
          'line-join': 'round',
          'line-cap': 'round',
      },
      'paint': {
          'line-color': '#00FF00',
          'line-width': 4
      }
   }); 
  } 
} 

this approach only show the last conditional result. so if the last loop is chicken , the map will only shown the else layer. Is there a way to fix this? Bcs i want to differentiate it by type from array data Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source