2

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

1
  • It's not a 2-d array, btw - it's an array of objects. Commented Jul 28, 2020 at 12:53

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

6 Comments

what's the difference a.ticketid > b.ticketid ? -1 : 1 and b.ticketid - a.ticketid?
@NikitaMadeev you can do that as well but you need to change the compare function accordingly developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
your answer is not working with my array of objects, do we need to do something else ?
what is not working exactly? if you check the code snippet above with a generic array of objects which is a subset of yours, it works fine, post the new output
New output is same
|
1

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

2 Comments

Doesnt work, i have updated my question, see edit :: 1
maybe parent object change definition of sort method, try to clone the array and sort them: let nar = tableData.map(i => i).sort((a, b)=> b.ticketid - a.ticketid)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.