Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting array element by indexes

I have been trying to solve this program. I have a list of objects that look like this. Adding elements to an array based on their index position.

let A = {index: 0} 
let B = {index: 0} 
let C = { index: 2} 
let D = {index: 2} 
let E = { index: 1}

So if A get pushed inside the array it takes over an array index position 0. However, when B get pushed in the array, it will take over an index position. [B, A], and so on. It is sort of like first go in, first come out, except get shifted to the left. However, I want to do something like this. [B, A, C], I want to add D to index position of C. [B, A, D, C]. A is at index position 1. I want to insert E to index 1. [B, E, A, D, C]

like image 643
spaceDog Avatar asked Mar 31 '26 23:03

spaceDog


1 Answers

  function insert(array, el) {
     let pos = 0;
     while(array[pos].index < el.index) pos++;
     array.splice(pos, 0, el);
  }

Just do insertion sort and use splice to add the element.

like image 152
Jonas Wilms Avatar answered Apr 03 '26 13:04

Jonas Wilms



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!