Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solution. Please let me know if there is a more efficient and reliable approach. It is crucial that the items are sorted by value to maintain consistency between the server (api) and client. This method will play a key role in our application's navigation, so ensuring browser compatibility, eliminating drawbacks, and reliability are important. As a fallback option, I can resort to using a regular switch-case statement, although it may not be ideal due to its complexity with multiple conditions. I would appreciate hearing your thoughts on this matter. Thank you in advance.

var dict = {
  "name3": 12,
  "name1": 5,
  "name2": 8
};

var items = sortProperties(dict);
//console.log(items);

var getItem = function(key, i) {

var index = 0;
var stop = true;
for (var j = 0; j < items.length; j++) {  
  
        if (items[j][0] == key) {
            index = j;
            break;// Found it
        }
    }    
console.log(index);
if((index + i) > -1 && (index+i) <items.length)
{
  return items[index+i][0];
}
else
{
 return 'empty';
 }  
}


console.log(getItem("name2",-1));
console.log(getItem("name2",+1));



function sortProperties(obj)
{
  // convert object into array
var sortable=[];
for(var key in obj)
if(obj.hasOwnProperty(key))
sortable.push([key, obj[key]]); // each item is an array in format [key, value]

// sort items by value
sortable.sort(function(a, b)
{
  return a[1]-b[1]; // compare numbers
});
return sortable; // array in format [ [ key1, val1 ], [ key2, val2 ], ... ]
}

Answer №1

As specified, objects do not have an inherent order of properties. Although the order is typically consistent in practice, it is not advisable to depend on it.

Reorganizing the properties each time you need to access the next or previous one is extremely inefficient. It is best to utilize an array to permanently store your sorted entries.

If the primary operations you intend to perform on your structure are next and previous, and there are numerous items involved, consider using a doubly-linked list for cost-effective operations.

For both efficient direct access and linked-list behavior, a compromise may be necessary. You could employ an array or Map for quick access, while also maintaining next and previous properties on all items for linked-list functionality. This approach may incur some overhead during structural changes, but can be acceptable if changes are infrequent.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

When attempting to redirect to a different page using setTimeout, the loading process appears to continue indefinitely

Currently, I am utilizing the following script: setTimeout(function(){ window.location.href = '/MyPage'; }, 5000); While this script successfully redirects me to /MyPage, it continuously reloads every 5 seconds. Is there a way to r ...

What is the best way to include multiple entries in a select2 form using ajaxform?

select2/3.5.2/ I had to repost this because my initial post was not formatting correctly. The tools in use are: A select2 form field that allows searching through multiple records A bootstrap popup modal containing a form for entering a new record if i ...

How can I access a method from another JavaScript file (service) in React JS's App.js to make API requests?

Just starting out with React js and trying to utilize REST API data. I've created a separate file named /shared/job-service.js for this purpose. My goal is to call a method from job-service.js in App.js and display the results on the UI. However, I&ap ...

Automatically selecting the map center while using the Drawing Manager feature for placing markers

My application utilizes the Google Drawing Library. When a user clicks on the Add New Marker Button, the Drawing Manager is activated allowing the user to generate a marker by clicking anywhere on the map. Subsequently, the following listener is executed: ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

Expanding the width of a Datatables within a Bootstrap modal

While working on my modal, I encountered an issue with the width of Datatables. Despite trying to adjust it to fit the modal size, it appears like this: Below is the jQuery code calling the Datatables: function retrieveTags(){ var identifier = $(&a ...

The use of event.returnValue in jQuery has been marked as deprecated

Every time I create a webpage using jQuery version , I encounter a warning message in the Console of Google Chrome. Is there a specific piece of code I can use to avoid this warning? Note that I am currently learning jQuery. The warning reads: event.retu ...

Displaying nested JSON data in a user interface using React

I have a complex nested JSON structure that I am using to build a user interface. While I have successfully implemented the first part, I am encountering difficulties with the second part. My Objective The nested JSON displays parent elements and now I a ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

JavaScript : Retrieve attributes from a JSON object

Situation : I have a JSON object with multiple properties and need to send only selected properties as a JSON string to the server. Approach : To exclude certain properties from the JSON string, I utilized the Object.defineProperty() method to set enumera ...

Display an array of objects using React within the columns of a Bootstrap grid

I am facing a challenge where I have an array of components that I need to render in separate cells. The number of elements in the array can vary, sometimes exceeding the limit of 12 cells in the Bootstrap grid system. In such cases, I need to create new r ...

Tips for editing events in the "react-big-calendars" component

I am looking to implement a feature where users can click on events in a calendar and then edit either the dates or event titles. Can this functionality be achieved using "react-big-calendar"? If not, are there any other packages you can recommend? <Cal ...

Capturing the Facebook Login Event to dynamically modify the content of the main webpage

My current project involves creating a Facebook-based login system using JavaScript. When a user clicks a button, I want one div to be replaced by another if the user is already logged in to Facebook. If they are not logged in, I prompt them to enter their ...

What causes the variable within the useEffect function to delay its value update?

const [inputValue, setInputValue] = useState(""); const previousInputValue = useRef(""); useEffect(() => { previousInputValue.current = inputValue; }, [inputValue]); return ( <> <input type="text" value={ ...

The AngularJS Service fails to properly convert incoming Json Responses into Model objects during piping

I have been studying AngularJS 17 and recently developed a login application. However, I am facing an issue where the server response is not being properly mapped to the object in the Model Class. Response: { "id": 1, "userName& ...

Could it be feasible to manage several ongoing asynchronous requests simultaneously?

Visualize a grid in which the user completes cell A1 and presses Enter to move to A2. As this happens, a request is sent to the backend to search a database and retrieve results for populating the remaining cells in row A. Meanwhile, I want the user to con ...

What is the best way to ensure that messages stay saved in my app for an extended

I am looking for a way to store messages sent through my small messaging app in a persistent manner. Currently, the messages are transferred from the front-end to a Node, Socket.io, and Express back-end. A friend recommended using Enmaps (), but unfortuna ...

What is the best way to align the variables in this JavaScript file with the variables in Flask/Python?

I have a JavaScript file that enables dynamic drop-down menus (i.e. selecting one option affects the others). However, I hard-coded the starting variables in this file to HTML elements 'inverter_oem' and 'inverter_model_name'. Now, I ne ...

Running CesiumJS is a straightforward process that can be done by

After diligently following the provided instructions, I managed to get cesium running locally. I then attempted the hello world example as shown: However, despite clicking on "open in browser," I couldn't see anything. It has been a constant struggl ...