...
Posted on Nov 11, 2023 | Category Javascirpt | 154
Share:

Don’t use index number for searching data in Array


In order to understand our today's problem we will write code for showing Sidebar menu items. Let’s say we have different User roles that allows users to see specific sections based on the roles given to their accounts. Let’s assume we have two users, UserA and UserB. UserA can view Dashboard and Report Download section and UserB can view Dashboard and Payments section in the MenuBar.

The above code shows menu based on the indexes of the Array items. It’s does the job but the conditional line in IF statemets has some flaws,

if(index === 0 || index === 1)
  1. Readability issue — It’s not possible to understand what is in the index 0/1. If the menu bar is huge like 20–30 menu items then we will need to go through the array of routes to find the 17th index for checking the menu item’s title.
  2. It will produce bug — if we just add a new menu item in the beginning of the routes then the menu items will be changed for all users. Role based users will see the menus that they do not have permission, also the menus for them will be missing.

How to avoid such issue?

Very Simple. Just filter out data by array data. In our case the array contains objects. Each object is a route and the routes have path, title and icon. For unique searching, title is not the option as it may change in future but route path is more likely to be stable so we can use the path for our conditional if statement.

if (menuItem.path === 'dashboard' || menuItem.path === 'payments')

Now we have better code readability that which menus will be shown to current user. Also we can add a new route to any position and it will not affect the view of rendered menu items.

Full code:


Tags: Web Development