No estoy encontrando ninguna solución. En todas partes muestra solo el primer y último elemento de una matriz.
Supongamos que tengo una matriz
[ { name: "Hero", Id: "hero" }, { name: "About", Id: "about" }, { name: "Proccess", Id: "process" }, { name: "Mission", Id: "mission" }, { name: "Skill", Id: "skill" }, { name: "Service", Id: "service" }, { name: "Work", Id: "work" }, { name: "Contact", Id: "contact" }, ] Aquí cada objeto tiene un Id. Supongamos que el ID activo es service . Cuando activo Id es service , entonces tengo que encontrarlo anterior y siguiente Id ( skill anterior, siguiente work ). Aquí tengo que encontrar el objeto anterior y el siguiente de acuerdo con la identificación activa. Aquí se puede cambiar el ID activo. Cuando se cambia la identificación activa, entonces tengo que encontrar los cambios en la identificación del objeto anterior y siguiente.
Creo que puedo aclarar la pregunta. Para el mio es dificil. Por favor, ayúdame.
Puede usar array.findIndex para obtener el índice actual, luego - y + eso para obtener el anterior y el siguiente respectivamente. También querrá tener en cuenta los índices fuera de los límites. La función que tengo devuelve undefined si el índice está fuera de los límites.
const arr = [ { name: "Hero", Id: "hero" }, { name: "About", Id: "about" }, { name: "Proccess", Id: "process" }, { name: "Mission", Id: "mission" }, { name: "Skill", Id: "skill" }, { name: "Service", Id: "service" }, { name: "Work", Id: "work" }, { name: "Contact", Id: "contact" }, ] const getPrevAndNext = (activeID) => { const index = arr.findIndex((a) => a.Id === activeID) if (index === -1) { return undefined } const prev = arr[index - 1] if (!prev) { return undefined } const next = arr[index + 1] if (!next) { return undefined } return [prev, next] } console.log(getPrevAndNext('service'))Puede usar el bucle for antiguo para iterar sobre la matriz y verificar si Id coincide, luego tome el index actual y agregue -1 para obtener prev y agregue +1 para obtener next . Como se muestra en el siguiente fragmento.
let array = [ { name: "Hero", Id: "hero" }, { name: "About", Id: "about" }, { name: "Proccess", Id: "process" }, { name: "Mission", Id: "mission" }, { name: "Skill", Id: "skill" }, { name: "Service", Id: "service" }, { name: "Work", Id: "work" }, { name: "Contact", Id: "contact" }, ]; for(let i = 0; i < array.length; i++){ if(array[i].Id === 'service'){ console.log('prev = ' + array[i-1].Id + ' next = ' + array[i+1].Id); } }