Navigatable Javascript objects array

Lilanga Gamage
BitsFactory
Published in
2 min readJan 1, 2019
Navigating a javascript objects array

Arrays help us to store multiple values in a single object, retrieve and manipulate them later. Since javascript is not a typed language, arrays can contain any type of data. Because of that Array methods in javascript provide collection management utility functions like pop, get by index, filter, forEach, slice etc.
But when we are using arrays to store a collection of objects, it is very helpful if we can create a navigatable pointer using given property value of an object and use navigation methods to navigate the array back and forth programmatically.

Navigating back and forth with objects array

This NavigatableObjectsArray provides that functionality by wrapping a given object array. In the constructor, we need to provide our base array, the object’s field name we are going to use for comparison to identify the initially selected object and the value of the initially selected object.

When we are wrapping objects array using NavigatableObjectsArray, we can use goNext and goBack methods to navigate back and forth from the initially selected object. If you came to the end of the navigation of the array, the function will return false on calling. You can use current, next and previous properties to retrieve the object in the current selection point and objects below and above the current selection pointer.

We can use goTo method to move cursor to a given object identified by selected field name value. goToEnd and goToStart methods will move cursor to last array element and first array element respectively.

Following is a simple example used in a reactjs component.

You can find a sample project in Codepen by following this URL.

That’s all folks

Hope this will help for someone to ease out development work. Please leave comments if you have any thoughts on this article or have any other use cases to address. And if you think this article is helpful, give me some claps 👏.

Thanks for reading…!

--

--

Lilanga Gamage
BitsFactory

Experienced software engineer, Solutions architect, IoT engineer, a tinker, SDR lover, Cyclist, OSS, Strong believer in sustainability goals.