1👍
✅
What is a.index
? Do you mean the array index?
I think you just want to find the index of the item in the array, then take the object at the next index:
nextOrder() {
const index = this.orders.findIndex(order => order.order_id === 234)
if (index === -1 || index === this.orders.length - 1) {
// No such order or no next order
return null
}
return this.orders[index + 1]
}
The previous order is at index index - 1
and the next order is at index index + 1
. To check if either order exists, you just need to check that the index is within the bounds of the array. An index i
is within the bounds of the array as long as 0 <= i <= (orders.length - 1)
.
The previous order exists if index - 1 >= 0
(cannot be negative index) and index - 1 <= array.length - 1
(cannot be greater than the last index of the array).
0👍
You can simply use findIndex
let arr = [{order_id: 234, text: 'foo'},{ order_id: 567, text: 'bar'}]
let findNextOrder = (id) => {
let index = arr.findIndex(({ order_id }) => order_id === id)
return index > -1 && index < arr.length - 1 ? arr[index + 1] : undefined
}
console.log(findNextOrder(234))
You don’t need sort based on your comment on question, also there’s no property named index on your object.
0👍
Try the following code,
let id = 234; // your id
let index = this.orders.findIndex(order => order.some_id === id);
console.log(this.orders[index + 1]); // give you the next object
Source:stackexchange.com