Is there a way to combine the advantages of both objects and arrays in JavaScript?

I have categorized data with unique IDs spread across different collections.

I am in need of quick and direct access to this data based on the ID, as well as efficient looping over the entire dataset.

var dataSetA = { 
  34523: { foo: 7, bar: 123},
  6435: { foo: 2, bar: 163},
  3123: { foo: 3, bar: 223},
  ... 
};

var dataSetB = { 
  34523: { baz: 1},
  6435: { baz: 4},
  3123: { baz: 6},
  ... 
};

Retrieving specific parts of data by ID is fast but iterating through all data entries can be slow.

var dataSetA = [ 
  { id: 34523, foo: 7, bar: 123},
  { id: 6435, foo: 2, bar: 163},
  { id: 3123, foo: 3, bar: 223},
  ... 
];

var dataSetB = [ 
  { id: 34523, baz: 1},
  { id: 6435, baz: 4},
  { id: 3123, baz: 6},
  ... 
];

When trying to retrieve specific data parts by ID from these arrays, it becomes slow as manual search is required. However, iteration speed over all data parts is fast.

Is there a way to achieve both fast direct access and rapid iteration?

Answer №1

Optimize your array for faster access:

var partList = [
    {id:23564, name:"apple", price:1.25},
    ...
];

var lookupPart = {};
partList.forEach(function(item,index) {lookupPart[item.id] = index;});

By pre-indexing the array, you can quickly iterate through partList, and also easily retrieve specific elements:

partList[lookupPart[23564]]

Answer №2

To optimize your object search:

let lookupPartA = { 
  34523: { foo: 7, bar: 123},
  ... 
};

let idList = Object.keys(lookupPartA);

By pre-indexing the object with lookupPartA, you can quickly locate ids and loop efficiently:

for (let i=0, length=idList.length; i<length; i++)
    lookupPartA[idList[i]]

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

Obtain asynchronous view model for component

Is it possible to retrieve a view model from the server and incorporate it into my component? I attempted to do so with the following code snippet, but it is not working as expected: function fetchViewModelFromServerAsync(){ setTimeout(function(){ ...

What is the preferred way to handle return values in a JQuery Ajax function - true or

Just a quick question about my AJAX function - should I include return statements in the code? Here's an example for reference: $.ajax({ type: 'POST', url: 'Application.cfc?method=runProcess', data: {'userID' ...

How can I update the value of one select tag when another select tag is changed?

My web page contains two select options as shown below. https://i.sstatic.net/kmDv3.jpg There are two select options labeled as #age1 and #age2, with age values ranging from 18 to 30. I want to ensure that when a user selects an age from #age1, the minim ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

The function GetSomething() in sequelize.js is displaying inaccurate values when used in a hasOne relationship, but is showing the correct values in a BelongTo

I'm encountering an issue where trying to fetch a Fluxo through a relationship in my CanaisCadastro results in the GetFluxo() function returning the incorrect row. On the other hand, using the foreign key in a findOne query returns the expected value. ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

Develop a Vue component for a fixed sidebar navigation

I am in need of a vertical navigation bar positioned to the left of my app's layout, with the content extending across the right side. However, I am currently facing an issue where the navbar is pushing all the content downwards. How can I resolve thi ...

Frequently, cypress encounters difficulty accessing the /auth page and struggles to locate the necessary id or class

When trying to navigate to the /auth path and log in with Cypress, I am using the following code: Cypress.Commands.add('login', (email, password) => { cy.get('.auth').find('.login').should(($login) => { expect($log ...

Angular 6 - detecting clicks outside of a menu

Currently, I am working on implementing a click event to close my aside menu. I have already created an example using jQuery, but I want to achieve the same result without using jQuery and without direct access to the 'menu' variable. Can someon ...

Activate event starting from parent and ascending through child nodes

When I have a table inside a <div class="timely"></div>, and within that table is a <th class="prev"><i>previous</i></th>, Chrome developer tools show an event listener on the <th>. However, Firefox developer tools ...

Which video format is best to enable transparent video on web applications for both desktop and mobile, ensuring compatibility with all browsers on these platforms?

My NextJS web application utilizes a transparent video, currently available in MOV and WEBP formats. Interestingly, WEBP works perfectly on Chrome (Desktop) while MOV is optimized for Safari (Desktop). However, I encounter difficulties when viewing the v ...

Error: Does Not Compile When Working With Multi Dimensional Arrays

This program is designed to determine if the sum of elements in the array equals zero. Each row in the multi-dimensional array will include 3 integers, with some potentially being negative based on user input. The program will only execute if integer n m ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Extract Item from Collection

In my current project, I am developing an application that allows users to add groups. Users can choose a group from a list, and that group will be displayed above it. (Check out this image) Now, I am looking to implement a feature where users can only se ...

Does the computation of "array[x][y]" always involve pointer arithmetic?

In my understanding of C programming: When a 2D array is declared as int array[x][y] = {0};, the program allocates a memory chunk that is x*y integers long. However, when a 2D array is created using malloc like this: int ** array = malloc(sizeof(int*) * ...

Guide to using JavaScript to multiply the values from two text fields and showing the result in a separate text field

Here is the code that I am currently using: <script type="text/javascript"> $(function() { $("#addAll2").click(function() { var add = 0; $("#discount") = $dis $(".amt2").each(function() { ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

Kendo Grid with locked height

Using a grid with some elements locked, we have established a CSS-defined minimum and maximum height for the grid. .k-grid-content { max-height: 400px; min-height: 0px; } An issue arises when setting the height of the locked grid. If the grid&a ...

Ensure that only a single onmouseover event is triggered when hovering over multiple elements

I want to create a simple code snippet like the one below: <span onmouseover="alert('hi')">Hello, <span onmouseover="alert('hello')">this</span> is a test</span> However, I need to ensure that when hovering ove ...