How do I sort a given array object in alphabetical order?

Asked

Viewed 790 times

-1

Hello! I’m a beginner and I’m making a site with HTML + CSS + JS and need to sort some items. It is a fictional site that aims to catch the Pokemons that are already being presented and ordered by ID. My challenge and so I need the help of you to know how to make "when the user clicks on the select "A-Z", this view must reorder using the Pokemon name as a criterion" by alphabetical order, if you click Z-A, the presentation is in reverse alphabetical order.

Following is git hub link

I’m using the data from src/data/Pokemon has the file Pokemon.js that I am using the data to present on the site.

Thanks for the help!

inserir a descrição da imagem aqui

  • 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.

  • array.Sort() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort You can also try other methods...

  • Thank you, I’ll do it!

2 answers

2

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:

1


Taking a look at your code, what you can do is use the method addEventListener to perform its function again showPokemon every time the select is amended.

Then you can take the value of the select field to know if it will be increasing or decreasing and use the method sort to order.

Let us know if you have any questions :)

As you said it is still starting, I will leave some links of references:

Method addEventListener:

https://developer.mozilla.org/en-US/docs/Web/API/Element/addEventListener

Method sort:

https://www.javascriptprogressivo.net/2019/01/Metodo-sort-Ordenar-array-JS.html

  • Hello! Thank you so much for looking at my code and doing the guidelines. I was totally lost. I will follow your tips, anything I warn you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.