You can use .map()
and .sort()
to create a list of names in alphabetical order, example:
let crescent = POKEMON["pokemon"].map(object => {
return object.name
}).sort()
And use .slice()
to copy this growing list and .reverse()
to sort decreasingly, example:
let decrescente = crescente.slice().reverse()
These lists present only names by which you can search in your Pokemons array within an iteration using .find()
, example:
crescente.forEach(poke => {
return POKEMON["pokemon"].find(x => x.name === poke)
})
The snippet Code below is simple but I think it fits your need:
// resevar o elemento <select>
let select = document.getElementById('sort-menu')
// reservar a <div> para mostrar pokemons
let container = document.getElementById('container')
// reservar a lista de pokemons
const listPokemons = POKEMON["pokemon"]
// matriz de nomes em ordem alfabética
let ascending = listPokemons.map(obj => {
return obj.name
}).sort()
// matriz de nomes em ordem reversa (cópia, não modifica a original)
let descending = ascending.slice().reverse()
// função para mostrar pokemons
function showPokemons(pokeInfo) {
let template = `<img src="${pokeInfo.img}" width="75px">`
container.innerHTML += template
}
// função iterar (crescente/decrescente)
function processPokemons(array) {
// loop
array.forEach(poke => {
// mostrar
showPokemons(listPokemons.find(x => x.name === poke))
})
}
// observar evento no seletor
select.addEventListener('change', (evt) => {
// limpar container
container.innerHTML = ''
switch(evt.target.value){
// crescente (e por padrão)
case 'a-z':
default:
processPokemons(ascending)
break
// decrescente
case 'z-a':
processPokemons(descending)
break
}
}, false)
// pre-carregar lista crescente por padrão
window.onload = function() {
processPokemons(ascending)
}
#container {
width: 450px;
min-height: 400px;
background-color: red;
height: auto;
}
<script src="https://daianalugocarvalho.github.io/data-lovers/src/data/pokemon/pokemon.js"></script>
<select id="sort-menu">
<option value="none">Ordenação:</option>
<option value="a-z">A - Z</option>
<option value="z-a">Z - A</option>
</select>
<div id="container"></div>
Source:
Hello, you can use the editor to inform code snippet of what you have already tried ... usually the community does not visit external services to evaluate code. The editor himself has a snippet to run snippets of HTML, CSS and Javascript. I recommend reformulating your question.
– Lauro Moraes
array.Sort() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort You can also try other methods...
– João Santos
Thank you, I’ll do it!
– Ya Oliveira