Home > Blockchain >  Sort an array element closest to known element based on it's index
Sort an array element closest to known element based on it's index

Time:09-01

Let's assume an array

Example 1 :

let arr = [101,102,104,103,105]
known_element = 104;

//Output  [104,102,103,101,105]

Example 2 :

let arr = [4,6,3,5,1,9,2,7,8]
known_element = 9;

//Output  [9,1,2,5,7,3,8,6,4]

Sort the above array in such a way,

  • known_element should be always at 0th element
  • second,third.. element should be closest to known_element by it's index not by value

Note: sorting should be done based on index closest to known_element.

CodePudding user response:

It makes sense to find location of known number first

var pos = arr.indexOf(known_element);

Then we are going to loop up and down, getting numbers from closest to farthest. Let's see to which side is longer length.

var length = Math.max(pos, arr.length - pos   1) 

Ok, our result array is ready (to be filled), lets loop

var result = [known_element];
for (var i = 1; i < length; i  ) {
  if (pos- i >= 0) {
    result.push(arr[pos - i])
  }
  if (pos   i < arr.length) {
    result.push(arr[pos   i]);
  }
}

I think that's it!

Test and let me know which edge case I forgot.

  • Related