Locate a specific item within an array using TypeScript

Looking for a more efficient solution to retrieve data from a collection in Typescript. The data is structured as follows:

myData:
{
  Id: string,
  Name: string,
  Address: string
  Salary: number
  phone: number
}

We have approximately 500 records, each with a unique ID. These records are displayed in a table showing only the ID and Name with checkboxes for each row.

When certain checkboxes are selected, I need to retrieve corresponding data by iterating through the list and taking action.

var selected: ImyData[];
for(var d in data)
{
  if(d.id == myId)
  {
    this.selected.id = d.id;
    this.selected.address = d.address
    this.selected.salary = d.salary
    return;
   }
 }

The current approach checks every element in the collection, which is not performance-effective. Any suggestions on how to improve efficiency in Typescript?

Answer №1

If you want to optimize your item lookup process in Javascript, consider creating a "dictionary" data structure (also known as assoc array, hashtable, or map). This allows for constant lookup time - O(1).

var selected = allItems[id];

You can initialize your dictionary using a for loop. This initialization only needs to be done once, and subsequent lookups will be very fast as they do not require a for loop.

Here is an example:

//Initialization, perform this step once!
var initObjects = [{ id: "id1", name:"name1" }, { id: "id2", name:"name2" }]

var dict = {};

for (i = 0; i < initObjects.length; i++) {
    var item = initObjects[i];
    dict[item.id] = item;
}

//Retrieving values. No loops needed! Constant lookup time - O(1)
console.log(dict["id2"])
console.log(dict["id1"])

(O(1) = constant lookup time independent of the size of your list. So the time taken to look up an item in a list with 100 or 1000000 items remains the same)

Answer №2

If you want to extract specific properties like "Id" and "Name" from an object, you can create a function that utilizes destructuring assignment within a for..of loop. This function will return the references to these properties if a match is found.

const myInfo = {
  Id: "001",
  Name: "John Doe",
  Age: "30",
  Occupation: "Engineer"
}

let targetId = "001";

const getIdAndName = (data, id) => {
  for (let {Id, Name} of [myInfo]) 
    if (Id === id) return {Id, Name}; 
  return `${id} not found in data`;
}

let result = getIdAndName(myInfo, targetId);

console.log(result);

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

What is the best way to include a minified bootstrap file in a TypeScript project?

Instead of using react-bootstrap, I only want to add the minified CSS. I went ahead and copied the original CSS file into my project, then added the path in the index.html, but unfortunately, it's still not working. <head> <meta charset=&quo ...

How can you alter the animation direction of a Bootstrap carousel slide?

Is it possible to create a reverse animation effect for a bootstrap carousel slide without changing the order of slides? 1 2 3 4 to 4 3 2 1 I just want the slides to appear in reverse order, is that achievable? The code snippet looks like this: < ...

What steps can I take to implement automation for this traffic light sequence?

document.getElementById('SwitchButton').onclick = automateLights; function turnOnRedLight() { clearAllLights(); document.getElementById('stopLight').style.backgroundColor = "red"; } function turnOnOrangeLight() { clearAllLights( ...

Replicate the drop file event

Can the drop event be simulated or faked using only JavaScript? How can this type of event be tested? Consider a drag-and-drop upload example like this one on this page. Is it possible to trigger the "drop" event with a file without actually dropping a fi ...

Tips on finding the most budget-friendly item in a Vue array

I'm working with an array called item.warehouse_positions that contains various prices and IDs. I want to display only one item.id with the lowest price. How can I achieve this? <div v-for='(item, index) in item.warehouse_positions' :key= ...

Navigating the From and To routes in Nuxt/Vue: A comprehensive guide

I am currently working on a Nuxt/Vue project. While inspecting in Dev Tools, I came across a From and To property. How can I access these properties within the Nuxt application? I have attempted to use this.$nuxt.$route, this.$nuxt.$router, and this.$rou ...

What is the process involved in executing the following script in Javascript?

var a; console.log(a); +function() { alert("Hello from IIFE!"); }(); console.log(a); a = 'Hi'; Output in console: undefined ALERT POPUP Hi Question: Should both instances of variable 'a' display undefined or should they both show ...

Learn how to create a button that will only submit a value when clicked using Node.js and EJS

Currently in my ejs file, I have a button that sends a value to app.js instantly when the program runs. However, I want it to only submit the value when clicked by the user. <% notesArray.forEach((note,i) =>{ %> <div class="note"> ...

employing a flexible array of gulp operations in run-sequence

I have a situation where I need to create gulp tasks with dynamic names and ensure that they run in sequence, not parallel. I have stored the task names in an array, but when I try to use run-sequence, I encounter an error. I suspect the issue lies in how ...

Utilizing an array to cycle through various images

Initially, I'm facing an issue with morscreens[i] not displaying the desired image from the array. When left as it is, it ends up showing a [<] button followed by "morscreens[i]" and then a [>] button. However, enclosing morscreens[i] in quotes ...

What is the most effective method to retrieve the UserName using Javascript?

Can someone please explain to me the difference between using session["user"].name and session["user:name"]? // I don't understand why we have to put the user session into the JavaScript global space :( var session = { user: { "Id":"d675c ...

Design buttons that are generated dynamically to match the style

I have a challenge in styling dynamically generated buttons. I've developed a component responsible for generating these dynamic buttons. const TIMER_PRESETS: Record<string, number> = { FIFTHTEENSEC: 15, THIRTYSEC: 30, FORTYFIVESEC: 45, ...

The knockout afterRender event triggers only on the initial rendering

Here is a basic ViewModel structure: export class ViewModel { public arr : KnockoutObservableArray<Dtos>; constructor() { this.arr = ko.observableArray<Dtos>(null); ko.applyBindings(this); this.init(); } ...

What is the best way to obtain the output of a JavaScript function on the server side?

I'm dealing with a JavaScript function that returns an array in this particular format: <script type="text/javascript"> function looping() { var column_num = 1; var array = []; $("#columns ul").not(" ...

Using ajax to submit a form in order to upload a file along with other fields

I've gone through all the questions and conducted extensive research, but unfortunately, I haven't been able to find a solution that works. Below is the HTML code snippet: <div id="createarea"> <form id="createform" action="index/c ...

Preventing AJAX/hash functionality for specific links exclusively within jQuery Mobile

I've come across some outdated solutions for this issue, but it seems they are no longer applicable to jQuery Mobile. My goal is to disable the AJAX/hashbang behavior for specific links only. I know that I can disable it globally like this: /** * ...

Scrollbar in an HTML selection tag

Is there a way to add a scroll bar to an HTML select box without using JavaScript? Alternatively, is there a JavaScript library that can achieve this behavior? Also, I'm looking for a redesign of the interface where I have two select boxes and items ...

Navigating around potential type errors when passing data for chart.js can be challenging. Here are some strategies to

I'm currently working on an application that includes a chart, and I'm facing an issue while trying to populate the chart with data from my store. The error occurs when I attempt to pass the chartData object through props to the data property of ...

Steps to Display Image in a Basic Grid Layout Without Using a Web Grid from a Database. Image is Stored in Byte Array Form

I am currently using ASP.NET MVC 4.0 and facing an issue where the image is not showing up in a simple grid. The grid appears empty even though I have saved the image in byte array format. While I can see other column details, the image is missing. Below ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...