Rearrange array elements according to the absolute difference with x i. e., the element having a minimum difference comes first and so on. Like I'm taking array [10, 5, 3, 9, 2, 3] and x = 7 then the absolute difference for every element should be =
7 - 10 = 3(abs)
7 - 5 = 2
7 - 3 = 4
7 - 9 = 2(abs)
7 - 2 = 5
7 - 3 = 4
So according to the difference with X, elements are arranged as [5,9,10,3,3,2].
I have tried this by the code below but still failing to do so:
function ar(a, x) {
var obj = {}, d, i, res;
for (i = 0; i < a.length; i++) {
d = Math.abs(a[i] - x);
obj[a[i]] = d;
}
res = Object.keys(obj).sort(function(a, b) {
return obj[a] - obj[b]
});
for (i = 0; i < res.length; i++) {
res[i] = parseInt(res[i]);
}
return res;
}
var o = ar([10, 5, 3, 9, 2, 3], 7);
console.log(o);
as you can see I'm making object which have only one key but values repeat here .. I can't find another way of solving it the answer I get is [5,9,10,3,2]:(..
as you can see I'm making object which have only one key but values repeat here
Objects can't have duplicate properties, so when you repeat a property it overrides the previous one with new value
You can simply use sort with Math.abs
let arr = [10, 5, 3, 9, 2, 3]
let x = 7
let sortByDiff = (arr,x) => arr.sort((a,b)=> Math.abs(a-x) - Math.abs(b-x))
console.log(sortByDiff(arr,x))