How do I a space between elements of flatMap function?
I am putting together a Pokédex application for a school project. My tutor suggested I use a flatMap function to display pokémon types and abilities as there is sometimes more than one.
However, they just get listed with commas between them and no spacing. I'd like to add some spacing between the pokémon types. Can anyone help me with how to do that?
Code below for how I get the data:
function loadDetails(pokemon) {
let url = pokemon.detailsUrl
return fetch(url)
.then(function (response) {
return response.json()
})
.then(function (details) {
pokemon.imageUrl = details.sprites.front_default
pokemon.height = details.height
pokemon.weight = details.weight
pokemon.abilities = details.abilities.flatMap(
(element) => element.ability.name
)
pokemon.types = details.types.flatMap(
(element) => element.type.name
)
})
.catch(function (e) {
console.error(e)
})
}
Code below for how it is displayed:
function showModal(pokemon) {
let modalBody = $('.modal-body')
let modalTitle = $('.modal-title')
//empty the modal before we start
modalTitle.empty()
modalBody.empty()
// create the elements we want in the modal
let nameElement = $(
'<h1 class="text-capitalize">' + pokemon.name + '</h1>'
)
let imageElement = $('<img class="modal-img">')
imageElement.attr('src', pokemon.imageUrl)
let heightElement = $(
'<p>' + '<b>Height: </b>' + pokemon.height + '</p>'
)
let weightElement = $(
'<p>' + '<b>Weight: </b>' + pokemon.weight + '</p>'
)
let typesElement = $(
'<p class="text-capitalize">' +
'<b>Types: </b>' +
pokemon.types +
'</p>'
)
let abilitiesElement = $(
'<p class="text-capitalize">' +
'<b>Abilities: </b>' +
pokemon.abilities +
'</p>'
)
// append the elements to the modal
modalTitle.append(nameElement)
modalBody.append(imageElement)
modalBody.append(heightElement)
modalBody.append(weightElement)
modalBody.append(typesElement)
modalBody.append(abilitiesElement)
$('#detailsmodal').modal()
}
Solution 1:
I used Array.join to control how the information is displayed, like so:
let abilitiesElement = $(
'<p class="text-capitalize">' +
'<b>Abilities: </b>' +
pokemon.abilities.join(', ') +
'</p>'
)
Solution 2:
What you currently have as result (with commas) is the string representation of an array. You could use join()
to join the array with a space.
const pokemons = ["Charmander", "Bulbasaur", "Squirtle"];
console.log(`${pokemons}`); // string representation of array (,)
console.log(pokemons.join(" ")); // spaces ( )