Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an object array by nearest values to x

I have an array of object and I want to sort that array by nearest value to X.

for example, this an array of objects:

[
 {"name" : "some 1", "value" : 12.4},
 {"name" : "some 2", "value": 11.4},
 {"name" : "some 3", "value": 10.5},
 {"name" : "some 4", "value": 11.4}
]

I want to sort it by nearest "value" to X.

Lets say I want to sort the array so the property "value" is nearest to 11. So the new order will be like:

[
  {"name" : "some 2", "value": 11.4},
  {"name" : "some 4", "value": 11.4},
  {"name" : "some 3", "value": 10.5},
  {"name" : "some 1", "value": 12.4}
 ]

because 11.4 is nearest to 11, then 10.5 then 12.4.

like image 724
fareed Avatar asked Jun 24 '26 11:06

fareed


2 Answers

You could sort by the absolute delta of the value and the wanted value.

var array = [{ name: "some 1", value: 12.4 }, { name: "some 2", value: 11.4 }, { name: "some 3", value: 10.5 }, { name: "some 4", value: 11.4 }],
    value = 11;
 
array.sort(({ value: a }, { value: b }) => Math.abs(a - value) - Math.abs(b - value));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 104
Nina Scholz Avatar answered Jun 25 '26 23:06

Nina Scholz


You can use the distances (the absolute value of the difference value - x) to sort the array like so:

arr.sort((a, b) => Math.abs(a.value - x) - Math.abs(b.value - x));
like image 20
ibrahim mahrir Avatar answered Jun 26 '26 01:06

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!