Home > Back-end >  Does sort alter my json array or does it return a sorted array
Does sort alter my json array or does it return a sorted array

Time:12-02

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 });
    }
}

CodePudding user response:

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"]

CodePudding user response:

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 });
  }
}
  • Related