user17786777
user17786777

Reputation:

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

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.

Upvotes: 2

Views: 2205

Answers (1)

Cjmarkham
Cjmarkham

Reputation: 9681

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

Upvotes: 6

Related Questions