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.
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; }
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With