Home > Mobile >  How to find previous and next object of an Array for a active object?
How to find previous and next object of an Array for a active object?

Time:01-03

I am not finding any solutions. Everywhere show just first and last element of an array.

Suppose, I have an 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" },
]

Here each object has a Id. Suppose active Id is service. When I active Id is service, then I have to find it previous and next Id (previous skill, next work). Here I have to find just previous and next Object according to active Id. Here Active Id can changed. When Active Id is changed then I have to find the changes previous and next object id.

I think I can clear the question. For mine it difficult. Please help me.

CodePudding user response:

You can use array.findIndex to get the current index, then - and that to get the previous and next respectively. You'll also want to account for out of bounds indexes. The function I have returns undefined if the index if out of bounds.

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'))

CodePudding user response:

You can use old fashioned for loop to iterate over array and check if if Id matches then take the current index and add -1 to get prev and add 1 to get next. As shown in below snippet.

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);
   }
}

  • Related