Tengo una lista de diferentes unidades:
const unitList = [1, 10, 36, 50, 20]; // all different numbers and all numbers are above 0 const unit = 13; // this is not included in unitList and not more that max number in unitList
Y quiero obtener el índice de la unidad en la que se debe colocar la unit
antes. por ejemplo:
const unit = 13;
devuelve el índice 4
porque debe colocarse antes 20
const unit = 35;
devuelve el índice 2
porque debe colocarse antes del 36
function getUnitPosition() { if(!unitList.length) return 'before add new unit'; const max = Math.max(...unitList); if(unit > max) return 'before add new unit'; const min = Math.min(...unitList); if(unit < min) return columns[0].id; for(let a = 0; a < unitList.length; a++) { console.log(unit , unitList[a], unit < unitList[a]) if(unit < unitList[a]) return columns[a].id; } }
Podría tomar el primer índice encontrado con un valor más pequeño que la unit
. Para cualquier otro valor más pequeño, verifique el valor para obtener el más pequeño.
const getIndex = (data, unit) => { let index; for (let i = 0; i < data.length; i++) { if ( unit < data[i] && (index === undefined || data[i] < data[index]) ) index = i; } return index; }, unitList = [1, 10, 36, 50, 20]; // 13 ^^ // 35 ^^ console.log(getIndex(unitList, 13)); // 4 placed before 20 console.log(getIndex(unitList, 35)); // 2 placed before 36