I have array of object in which i need to sort based on condition using javascript.
I need to sort the others list based on tariffId but in the order 7201, 7202, 7203, 7205, 7204
means always 7204 is the last.rest can be in asc order
var arrobj = [
{id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7204}, {place: "IN", tariffId:7203} ] }
{id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7204}, {place: "IN", tariffId:7205} ] }
{id:1, others: [ {place: "IN", tariffId:7202}, {place: "IN", tariffId:7204}, {place: "IN", tariffId:7201} ] }
]
Expected output
{id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7203}, {place: "IN", tariffId:7204} ] }
{id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7205}, {place: "IN", tariffId:7204} ] }
{id:1, others: [ {place: "IN", tariffId:7201}, {place: "IN", tariffId:7202}, {place: "IN", tariffId:7204} ] }
]
Tried
var result = arrobj.map(e =>
e.others.sort((a,b)=> a-b).map(i => i))
;
2
Answers
You had it almost already, just need to move 7204 to the end of the new sorted array.
There are multiple ways of doing this, but here a simple solution might be to transform 7204 into a large number during sort.
eg.
A little side note: your using
map
here, but you might not realise your still mutating the original array. If you doconsole.log(arrobj)
you will see what I mean. A small fix for this would be to do ->