Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript : Rearrange array elements according to the absolute difference with x

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]:(..

like image 683
Anonymus Avatar asked Sep 03 '25 01:09

Anonymus


2 Answers

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))
like image 172
Code Maniac Avatar answered Sep 04 '25 14:09

Code Maniac


Just define your distance function:

const dist = x => Math.abs(x - 7);

and pass the difference of it applied to both argument of the sort method.

arr.sort((a, b) => dist(a) - dist(b));

See MDN for more info on the sort method.

const arr = [10, 5, 3, 9, 2, 3];
const dist = x => Math.abs(x - 7);
const sorted = arr.sort((a, b) => dist(a) - dist(b));

console.log(sorted);
like image 38
Rúnar Berg Avatar answered Sep 04 '25 15:09

Rúnar Berg