The Inner Workings of JavaScript Objects and Organized Numerical Keys

I've scoured numerous other resources with no luck in finding a satisfactory answer to this query.

It's common knowledge that JavaScript objects arrange their integer keys in ascending order, not in the order they were inserted.

const lookup = {}

lookup['1'] = 1
lookup['3'] = 3
lookup['2'] = 2

console.log(Object.keys(lookup)) -> ['1', '2', '3']

That part is straightforward. However, what is the big O notation for the internal sorting process? There must be some sort algorithm working behind the scenes to organize the keys as they are added, but I'm unable to determine which one.

When it comes to Array.sort(), Insertion Sort is used for arrays with a length of 10 or less, while Quick Sort is employed for arrays exceeding a length of 10.

Yet, Array.sort() rearranges an object's keys based on the sorting of its values.

So, how exactly does JavaScript sort its keys upon insertion?

Answer №1

(I am a developer specializing in V8.)

Like many things, it all depends.

If the integer-keyed properties are tightly packed, the object will utilize an array to store them efficiently. This can be likened to a form of "radix sort", where elements are stored in such a way that they end up sorted without the need for explicit sorting steps. When assigning a value with lookup[2] = ..., it goes directly into the corresponding slot of the array. If the array is too small, a new one is created and existing entries are copied over; however, this operation occurs infrequently, maintaining an average insertion cost of "O(1) amortized". Retrieving the list of integer-keyed properties from the array already provides them in sorted order.

In cases where the integer-keyed properties are sparse, the object switches to using a dictionary as its storage mechanism. Hash-based dictionaries maintain entries in their own unordered manner, requiring explicit sorting steps for operations like Object.keys(). Currently, C++'s std::sort is utilized for sorting in this scenario, though this could change based on various factors including V8's implementation and the underlying standard library used by std::sort.

It was once said that Array.sort() implements Insertion Sort for lengths <= 10 and Quick Sort for lengths > 10.

This information is outdated since we adopted TimSort in 2018.

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

extracting values from an array

Here is the array that I have: $pv->orderRecordsArray = array(); foreach($order->records as $i=>$orderRecord){ $pv->orderRecordsArray[] = $orderRecord->orderRecordID; } // print_r($pv->orderRecordsArray) for example // shows ...

The app mounting process encountered an error: the mount target selector "#app" did not return any element

Could you assist me in solving this issue? I've been struggling to find a solution for a while now. Where should I place my <script src="{% static 'js/custom-vue.js' %}"></script> to address the error indicated in the image below ...

Transforming an individual array into a multi-dimensional array

Just to be upfront, I had to figure this out for a project. I needed to convert a single array into a multidimensional array within a method. To solve the problem, I came up with the following code by first returning it to another one-dimensional array and ...

When using React hooks forms, setting default values from a reduced array does not automatically populate the form. However, manually entering the same object into the form does

As I work with react hooks forms, I am facing a challenge in setting default values for a form generated by mapping over an array to output the inputs. After reducing the array into an object format like {name0:"fijs",name1:"3838"...}, manually passing thi ...

Comparison between Java's arrayList and C++'s vector

Question: What is the equivalent of Java's ArrayList in C++? While going through the book "Cracking the Coding Interview," I noticed that all the code examples are in Java and heavily utilize ArrayList. In a coding interview for a position where ...

Converting a character array to a Java string can be done using printf for integer types, however, it does

Our vendor provides us with an API that includes a struct defined as: typedef struct { char duo_word[8]; } duo_word; This data structure is sent to us by the vendor, and we then need to pass it to our Java application using JNI. printf("Number: ...

I am encountering a "TypeError: topics.forEach is not a function" error when attempting to retrieve metadata for topics using my kafkajs client in Node.js/express.js. Can anyone help me understand why

I am attempting to retrieve the metadata of my Kafka brokers' topics using the kafkajs admin client within my Node.js + express.js server. Here is the content of my index.js file, serving as the main entrypoint for npm: 'use strict'; cons ...

What is the best way to have my sliding panel automatically close when I click outside of it?

I have created a sleek sliding navigation panel for my website that appears when the screen width is reduced. Although I am satisfied with how it functions currently, I would like the panel to close when the user clicks/taps outside of it. What adjustments ...

Guide to customizing the value appearance in tooltip axispointer chart (angular)

Check out the code snippet here: https://stackblitz.com/edit/angular-ngx-echarts-zn8tzx?file=src/app/app.component.ts view image description I am looking to format and add the text "UPLOAD" and "DOWNLOAD" below the date and time. For instance: 2020-02- ...

Show a directional indicator on hover in the date selection tool

I am currently using a datepicker that looks like this: https://i.sstatic.net/XsrTO.png When I hover over it, three arrows appear to change days or show the calendar. However, I would like to remove these arrows. Here is the code snippet: link: functi ...

Is it necessary to separate Lodash orderby functions to ensure they function correctly?

For some reason, I'm having trouble sorting my data using lodash in my front-end client code. All the examples I've come across don't involve working with data in an interface, so I can't figure out where I'm going wrong. Let&apo ...

Extract the content of an element and incorporate it into a script (AddThis)

HTML: <div id="file-section"> <div class="middle"> <p class="description"> Lorem ipsum... </p> </div> </div> jQuery: var share_on_addthis = { description: $('#file-section ...

Implementing role-based authentication in Next.js using Next-auth and Firebase

Currently, I'm in the process of integrating role-based authentication using NextAuth.js into my Next.js application. Despite following the provided documentation meticulously, an error (in profile snippet and callback snippet which I copied from next ...

"VueJS application can now be restarted with the simple push of a

Is there a way to reload the application in VueJS when a button is pressed? I've attempted the following: this.$nextTick(() => { var self = this; self.$forceUpdate(); }); However, $forceUpdate() does not serve the purpose I need. ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

Having trouble retrieving data about my marker through react-leaflet

Hello, I am currently working on accessing information about my marker using React and react-leaflet, which is a library based on Leaflet. I initially tried to utilize useRef, but unfortunately it did not provide the expected results. When attempting to us ...

Establishing the initial value of a <select> element

My webpage features a table that displays the details of past order history, with columns for Order, Date, and Review. For the Review column, I am seeking to add a select dropdown with various options. Upon the initial page load, I would like the select d ...

Is it possible to merge multiple time columns into one in SQL while keeping the metadata intact?

Looking for a way to consolidate timestamps from four different columns in a SQL database table while maintaining id and metadata information. id | a_time | b_time | c_time | d_time | metadata1 | metadata2 1 | 8 | 7 | 2 | 4 | a ...

The generated hook in vuejs is throwing an error stating that window/localstorage is not defined

My goal is to save an authenticated user to local storage and then load them into Vuex on the next page load. created () { let user = window.localStorage.getItem('user') if(user) { this.setUser(JSON.parse(user)) } } I initia ...

Solve problems with limitations on ng2-dnd drop zones

I successfully integrated drag and drop capabilities into my Angular 4 application using the ng2-dnd library. Within my application, I have containers that can be sorted, as well as individual items within each container that can also be sorted. My goal i ...