# How to sort by Math.abs and newest date?

I googled and research for two days but I don’t find any example like this case:

Can someone help me?

Thanks alot!

``````const data = [
{ date: '5/20/2019', number: 20 },
{ date: '5/20/2015', number: 22 },
{ date: '5/20/2021', number: 18 },
{ date: '5/20/2021', number: 23 }
]
let results = data.sort((a, b) => {
return Math.abs(20 - a.number) - Math.abs(20 - b.number);
});
console.log(results);
/*
The results should like this:
[
{ date: '5/20/2019', number: 20 },
{ date: '5/20/2015', number: 22 },
{ date: '5/20/2021', number: 18 },
{ date: '5/20/2021', number: 23 }
]
*/
/* In this case 22 and 18 are same ratio with 20 and I will want get the results order by newest date like this:
[
{ date: '5/20/2019', number: 20 },
{ date: '5/20/2021', number: 18 },
{ date: '5/20/2015', number: 22 },
{ date: '5/20/2021', number: 23 }
]
*/
``````

There’s one more step needed. Either in the current sorting function - to consider dates if the numbers have the same `Math.abs`, or by adding another `sort` call before the current one - sorting all entries by the date.

check this out

``````let results=data.sort((objA,objB)=>{

function parseDate(obj){
let date=obj.date.split('/').map(n=>{
if (n.length<2) n='0'+n
return n
})
date=date[2]+date[0]+date[1]
return date
}

function parseN(obj){
return Math.abs(20 - obj.number).toString()
}

let a=parseN(objB)+parseDate(objA)
let b=parseN(objA)+parseDate(objB)

return b-a
})
``````

It returns the result you anticipate, but i havent test it for malfunctions and im not entirely sure the logic is stable, or even, how you want the logic to be. Do you want the objects to be sorted by number ascending and date descending order?

This is how the code is expected to behave, but i kinda earned the final result by hit and miss.
I made two functions, `paraseDate` and `parseN`. The first extracts a date from an object and returns a string in the following format- “YearMonthDay”. Using it, you can compare two objects dates(“YearMonthDay”-“YearMonthDay”) and you can use the result to determine which date is greater(newest). The `parseN` function extracts an object number and returns `Math.abs(20 - obj.number).toString()`. I convert to string format, so i can concatenate with the “YearMonthDay” string, as i need to compare both at the same time. In the end it works bit counter-intuitive by comparing two values, each produced by concatenating one object parsed number to the other object date value and then compares the two results, to finally determine the sort order.

Thanks for you reply.
This question was resolved by GrumpyGuss here: https://www.reddit.com/r/learnjavascript/comments/nlxuyg/how_to_sort_by_mathabs_and_newest_date/gzlfscl?utm_source=share&utm_medium=web2x&context=3

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.