user2828442
user2828442

Reputation: 2515

Sorting of two-dimensional Array not working

I have this array, I want to sort it ticketid wise, which is a number. Below is the code I am trying

    console.log(this.tableData);
    var filtered_tableData = this.tableData.sort((a, b)=> a.ticketid- b.ticketid)
    console.log(filtered_tableData);

But it is not sorting as expected.

Here is my array:

enter image description here

Edit 1

After trying this code, my result array still remains the same

    console.log(this.tableData);
    var filtered_tableData = this.tableData.sort((a,b) => (a.ticketid > b.ticketid) ? 1 : ((b.ticketid > a.ticketid) ? -1 : 0)); 
    console.log(filtered_tableData);

Please note this.tableData and filtered_tableData result is same in console.log.

See image below

enter image description here

Upvotes: 2

Views: 117

Answers (3)

MohammedElmsellem
MohammedElmsellem

Reputation: 31

descending sort should be b.ticketid - a.ticketid:

let ar = [{ticketid:3},{ticketid:5},{ticketid:2}]
    var filtered_tableData = ar.sort((a, b)=> b.ticketid - a.ticketid)
    console.log(filtered_tableData);

Upvotes: 1

Karim
Karim

Reputation: 8632

Change the sort callback to specify a descending order, and you don't need a new reference variable (filtered_tableData) because the sort acts on the original reference tableData

const tableData = [{ ticketid: 24}, { ticketid: 12 }, { ticketid: 90 }]
tableData.sort((a, b) => a.ticketid > b.ticketid ? -1 : 1)
console.log(tableData)

Upvotes: 2

Relu
Relu

Reputation: 37

Have you tried variations of:

sort((a, b)=> b.ticketid - a.ticketid)
sort((b, a)=> b.ticketid - a.ticketid)
sort((b, a)=> a.ticketid - b.ticketid)

My background is C# so it's just a shot in the dark but thought it might help.

Upvotes: 0

Related Questions