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

124
Visualizações
Does sort alter my json array or does it return a sorted array

I am trying to sort a json array on my Table header click. I am trying to follow this web article. My function runs but the array is never changed. Here is the function:

function setInvoiceSortField(field) {
    console.log(field);
    let sortedInvoices = this.state.invoiceList;
    if (field !== null) {
        sortedInvoices.sort((a, b) => {
            console.log(`a ${a[field]}`);
            console.log(`b ${b[field]}`);
            if (a[field] < b[field]) {
                return -1;
            }
            if (a[field] > b[field]) {
                return 1;
            }
            return 0;
        });
        this.setState({ invoiceList: sortedInvoices });
    }
}

I can post an example of the json array and/or the entire .js file if needed. Is .sort() changing sortedInvoices or does it return a sorted array? Any hints or help are extremely appreciated!

UPDATE

I added an if to check to see if they match post sort and they do.

function setInvoiceSortField(field) {
    console.log(field);
    let sortedInvoices = this.state.invoiceList;
    if (field !== null) {
        sortedInvoices.sort((a, b) => {
            console.log(`a ${a[field]}`);
            console.log(`b ${b[field]}`);
            if (a[field] < b[field]) {
                return -1;
            }
            if (a[field] > b[field]) {
                return 1;
            }
            return 0;
        });
        if (sortedInvoices === this.state.invoiceList) {
            console.log("matched")
        }
        this.setState({ invoiceList: sortedInvoices });
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

From the MDN website:

The sort() method sorts the elements of an array in place, and returns the sorted array. Example copied.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
about 4 years ago · Juan Pablo Isaza Relatório

0

Since you are directly assigning the array(this.state.invoiceList) to sortedInvoices it will be done by reference. So even though your array(sortedInvoices) is different from invoiceList, both the references are same. Hence changes are not reflected.

function setInvoiceSortField(field) {
console.log(field);
let sortedInvoices = [...this.state.invoiceList];
if (field !== null) {
    sortedInvoices.sort((a, b) => {
        console.log(`a ${a[field]}`);
        console.log(`b ${b[field]}`);
        if (a[field] < b[field]) {
            return -1;
        }
        if (a[field] > b[field]) {
            return 1;
        }
        return 0;
    });
    this.setState({ invoiceList: sortedInvoices });
  }
}
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