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