Sorting by number or date in indexedDB may lead to unexpected results due to the

I have set up an index in my database called time on the created_at field:

var os = thisDB.createObjectStore(name, { keyPath :  "id" });
os.createIndex("time", "created_at", {unique: false });

Instead of storing the time as a standard date format, I convert it to a unix integer:

entry['created_at'] = Date.new(entry['created_at']).unix();
var request = sto.add(entry);

This results in the data appearing like this in the console:

My issue lies in retrieving the data in either ascending (asc) or descending (desc) order based on the created at time:

When I use a cursor to loop through the data:

function open_cursor(){
  var objectStore = ENTRYDB.transaction('entries').objectStore('entries').index('time');
  var request = objectStore.openCursor();
  request.onsuccess = function(event) {handle_open(event)};
}
function handle_open(evt){
  var cursor = evt.target.result;
  if (cursor) {
    console.log(cursor.value);
    cursor.continue();
  }
}

The data is not sorted by the created at time as expected, and appears random instead! Any assistance on this matter would be greatly appreciated. THANKS

Answer №1

To sort in ascending or descending order using the openCursor function, simply provide the second parameter: index.openCursor(undefined, "next") for ascending or "prev" for descending.

Sorting should be effective on the index even without specifying next or prev (where next is the default). When invoking openCursor on the index, it iterates through them in a similar way to how Chrome DevTools displays them when selecting the "time" index in the debugger.

If you are using the shim (perhaps for iOS/android), it's worth noting there may be issues with sorting functionality. You can check out more information about this at https://github.com/axemclion/IndexedDBShim. However, if you're unsure whether this applies to your situation, feel free to disregard this paragraph.

EDIT It seems unlikely that you are using the shim since I can see a screenshot of IndexedDB from Chrome DevTools, which wouldn't be possible if the shim were in use due to its different storage mechanism).

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

The function client.guilds.find cannot be located

Hey there! I've been tasked with working on a Discord bot that requires several dependencies to function properly. I've installed the necessary dependencies and attempted to run the bot using 'forever -o out.log bot.js'. However, I enc ...

Changing or toggling the visibility of links once the week is finished

I have a total of 4 links available, but I want to display only one link at a time, highlighting a different lunch option every week. Once all 4 weeks have passed, the first lunch menu will be shown again, starting from Monday. <div class="wrapper& ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

Tips for implementing automatic line wrapping in a PDF document using React-PDF

I am experiencing an issue with a PDF rendering where very long words are not wrapping onto a new line, instead overflowing the container and disappearing off the page. Below is the setup causing this problem. The styles are listed followed by the actual ...

`Issues encountered with resizing the menu``

Looking to create a unique restaurant horizontal list bar for my application. The goal is to have a horizontal menu that displays 3 options on the screen at a time, with the middle one being the largest and the two flanking it smaller in size. As I scroll ...

nodemon breaks down frequently while anticipating changes in files

After cloning a project that I finished 2 months ago, I am facing an issue where nodemon won't run. Despite trying to close npm using task manager on Windows and running it again, the error persists. I am also utilizing MongoDB as my database. If any ...

What to do when VueJs computed method throws an error: "Cannot access property 'words' of undefined"?

Here is some pseudo code that I've written: var vm = new Vue({ el: '#test', data: { words: [{name:'1'}, {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}], } ...

Tips for adjusting the horizontal position of a grid item within a map() loop

I am trying to align the text in my Timeline component from Material Ui always towards the center of the timeline. The TimelineContent contains Paper, Typography (for title and description), and an image. Currently, I have multiple TimelineContent element ...

What is the most effective way to retrieve 'this' within an object method that is being used as a callback function?

I am currently working on a word game project to enhance my understanding of JavaScript, especially since I am new to it. To facilitate user interaction, I am utilizing the NPM package prompt (https://www.npmjs.com/package/prompt). Coming from an OOP back ...

Encountering the error message "Unable to access /" on the browser when using express router

Just started working with the express Router for the first time. Here is my route.js: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('home page'); }); module.e ...

Data loading issue with asp.net mvc Ajax

I am currently facing an issue while attempting to fetch data from the controller using ajax. Controller [HttpGet] public ActionResult GetServices() { var data = _bbdb.ListServices.Where(d => d.Status == true).ToList(); return Json(data, JsonR ...

Seems like JavaScript's .active functionality is failing to function properly in my case

I'm encountering an issue with my website's homepage. I have a list of services displayed, and the intention is for a description to appear when one of the services is clicked. However, clicking on the buttons does not trigger the expected action ...

What is the best way to send the input text to the filter component in my React application?

I am currently working on developing an application utilizing the "Rick and Morty API" to display a list of characters with various attributes such as gender, alive status, images, etc. My main goal is to implement a search bar that allows users to search ...

Verify the checkbox for validation is shown exclusively

I am currently facing an issue with a form that includes a checkbox, which is only displayed under certain conditions. I want to ensure that the checkbox is checked only when it is visible, and if not, the form should be submitted upon clicking the submit ...

Convert the property that starts with XX from XML to JSON

I am currently working on a function that looks like this request.execute('[someSP].[spSomeSP]', function(err, dataset) { _.map(dataset, function(items) { console.log(items); }); }); When the _.map(...) is executed, it retu ...

jQuery problem with setting and redirecting users if cookie value is missing

On my home page, there is a script that checks two things when a user visits our site: If the screen size is less than 800 pixels, they are redirected to the mobile site. If they have previously visited the mobile site and selected "View Full Site," ...

Changing from Basic to JavaScript?

Good evening, I am looking to convert this example code from Basic to JavaScript. Since JavaScript does not support the "Go To" command, I would appreciate it if you could help me with the translation. Thank you in advance. 10 x = 1666.66 20 y = 1.007897 ...

Retrieve a specific value from an array within Firestore

I am facing an issue where I can only retrieve the values I need from the array by adding a specific string like "اقلام" or "سبورة". However, I want the value to be passed as a prop from another component or screen. Is there a way to resolve this ...

Run a Python script to capture mouse coordinates using Selenium

Greetings, I am currently utilizing selenium webdriver to retrieve the X,Y coordinates of the cursor at a specific moment on the webdriver screen. However, I am facing challenges with the implementation of a method that involves using driver.execute_script ...

Activate the class only on the current element

I need help with a specific functionality on my website. I have multiple sections with content and buttons, and when a button is clicked, I want to add an active class to the corresponding content section within the same row. <div id="1" class="row"> ...