Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
Search JS array without losing index - Working Codepen Demo uses fetch() and Alpine.js

I have a working CodePen demo here: https://codepen.io/JosephAllen/pen/vYmQpWL?editors=0010

This demo:

  1. Fetches users from an API
  2. Sorts the list based on a "points" property
  3. And then displays that sorted list utilizing the index as a "rank". In other words, if your index is zero, you're in first place.

There is an input field to search and filter the list, but filtering the array creates a new index for each user – which ruins the whole idea of a rank.

How can I keep the rank and search feature without creating new indexes for users?

If I was the author of the API I would just include the rank as a property, but I'm not.

My fetch function:

getUsers() {
    fetch(`https://trafficthinktank.com/wp-json/mjtw/v1/community`)
        .then((res) => res.json())
        .then((data) => {
            this.isLoading = false;
            this.users = data.sort((a, b) => b.points - a.points);
            // this.users = this.users.map(user => ({ visible: true, ...user }));
            console.log(this.users);
        });
    0;
}

My filter function:

get filteredUsers() {
    if (this.search === "") {
        return this.users;
    }

    return this.users.filter((item) => {
        return item.name.toLowerCase().includes(this.search.toLowerCase());
    });
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Indexes can not remain constant since there can't be an array with missing number in its index sequence. Nevertheless, you can simply map your array and keep indexes inside. Look at this, might be helpful:

getUsers() {
    fetch(`https://trafficthinktank.com/wp-json/mjtw/v1/community`)
        .then((res) => res.json())
        .then((data) => {
            this.isLoading = false;
            this.users = data.sort((a, b) => b.points - a.points);
            // this.users = this.users.map(user => ({ visible: true, ...user }));
            this.users = this.users.map((entity, index) => ({index, entity}));
            console.log(this.users);
        });
    0;
}

and then you can filter like this

get filteredUsers() {
    if (this.search === "") {
        return this.users;
    }

    return this.users.filter((item) => {
        return item.entity.name.toLowerCase().includes(this.search.toLowerCase());
    });
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda