'Calculating the index to insert into a sorted array
I want to insert new elements not at the end of the array, but directly into a suitable position.
To do this, I use the .splice() method, in which I pass the callback function getSortPos()
acc.splice(getSortPos(acc, newAccount, compareAccounts), 0, newAccount)
This function takes an array, a new element and a compare function and calculates the appropriate position for inserting the new element
const getSortPos = (arr, el, cmpFn) => {
let pos = 0;
if (!arr?.length) {
return pos;
}
while (cmpFn(arr[pos], el) < 0) {
pos++;
}
return ++pos;
}
The solution seems to work at first glance but I think it has some flaws and does not look elegant.
I would be extremely grateful for any tips
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
