What is the best way to efficiently filter and process two arrays of objects?

I am struggling to efficiently match and update objects from 2 arrays with different key combinations. Despite trying various .filter combinations, I have not been successful yet. My goal is to update the masterList based on the selectionList.

for (let selObj of selctionList) {
    for (let obj of masterList) {

        if (selObj['n'] == obj['name']) {
            obj['checked'] = true;
            obj['cost'] = selObj['r'];
            obj['qty'] = (selObj['q'] ? selObj['q'] : 1);
            break;
        }
    }
}
for (let obj of masterList) {
    if (!obj['checked']) {
        obj['checked'] = false;
    }
}

Sample Data

`masterList = 
[{"id":459,"cost":250,"name":"Coke"},
{"id":460,"cost":60,"name":"Cookies"},
{"id":461,"cost":100,"name":"Pizza"},
{"id":462,"cost":250,"name":"Bread"},
{"id":463,"cost":150,"name":"Sausage"},
{"id":464,"cost":150,"name":"Juice"}];
selectionList = [{"q":1,"r":350,"n":"Coke"}
{"q":2,"r":550,"n":"Bread"}]`

Output :

`[{"id":459,"cost":350,"name":"Coke", "checked" : true,"qty":1},
{"id":460,"cost":60,"name":"Cookies","checked" : false},
{"id":461,"cost":100,"name":"Pizza","checked" : false},
{"id":462,"cost":550,"name":"Bread","checked" : true,"qty":2},
{"id":463,"cost":150,"name":"Sausage","checked" : false},
{"id":464,"cost":150,"name":"Juice","checked" : false}]`

Answer №1

To optimize the time complexity of this code from O(n²) to O(n), consider implementing a hash map for direct access to entries in the masterList based on their names:

const masterList = [{"id":459,"cost":250,"name":"Coke"}, {"id":460,"cost":60,"name":"Cookies"}, {"id":461,"cost":100,"name":"Pizza"}, {"id":462,"cost":250,"name":"Bread"}, {"id":463,"cost":150,"name":"Sausage"}, {"id":464,"cost":150,"name":"Juice"}];
const selectionList = [{"q":1,"r":350,"n":"Coke"},{"q":2,"r":550,"n":"Bread"}];

// Utilize a Map to index masterList by name
const indexed = new Map(masterList.map(o => [o.name, o]));
// Initialize the checked property first
for (const obj of masterList) obj.checked = false;
// Iterate and perform lookups in the Map.
for (const {q, r, n} of selectionList) {
    const obj = indexed.get(n); // Lookup is constant time 
    if (!obj) continue;
    obj.cost = r;
    obj.qty = q || 1;
    obj.checked = true;
}

console.log(masterList);

Note: The inclusion of a checked property may be unnecessary since matched objects already have a qty property, which distinguishes them from others. In future code, you can easily verify this using:

checked = 'qty' in obj;

Answer №2

Speeding up the calculation with a practical approach using lodash's keyBy.

const mainList = [{"id":459,"cost":250,"name":"Coke"}, {"id":460,"cost":60,"name":"Cookies"}, {"id":461,"cost":100,"name":"Pizza"}, {"id":462,"cost":250,"name":"Bread"}, {"id":463,"cost":150,"name":"Sausage"}, {"id":464,"cost":150,"name":"Juice"}];
const listSelection = [{"q":1,"r":350,"n":"Coke"},{"q":2,"r":550,"n":"Bread"}];

const selectionMap = _.keyBy(listSelection, "n");
const result = mainList.map(mainItem => {
  // check if item is selected from main list
  const selectedItem = selectionMap[mainItem.name];
  if(selectedItem === undefined){
    // If not selected, return relevant information.
    return {
      ...mainItem,
      checked: false
    };
  }
  // if selected, return checked: true and quantity info (default to 1).
  return {
    ...mainItem,
    checked: true,
    qty: selectedItem['q'] || 1
  };
});

console.log(result);

Output:

[[object Object] {
  checked: true,
  cost: 250,
  id: 459,
  name: "Coke",
  qty: 1
}, [object Object] {
  checked: false,
  cost: 60,
  id: 460,
  name: "Cookies"
}, [object Object] {
  checked: false,
  cost: 100,
  id: 461,
  name: "Pizza"
}, [object Object] {
  checked: true,
  cost: 250,
  id: 462,
  name: "Bread",
  qty: 2
}, [object Object] {
  checked: false,
  cost: 150,
  id: 463,
  name: "Sausage"
}, [object Object] {
  checked: false,
  cost: 150,
  id: 464,
  name: "Juice"
}]

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 optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Ways to verify if any items in an array are present in a different array

I have two arrays of objects and need to determine if certain items are contained in another array. If any of them are not found, the result should be false. const arr = [ {full_name: 'Test'}, {full_name: 'Test1&apo ...

Passing an ID via Link to retrieve data with getServerSideProps in Next.js

I have several alert components. From each of these components, I aim to pass the itm._id and receive it in [itm].jsx within the same folder. In [itm].jsx, I intend to utilize it in the getServerSideProps function for fetching data. Below is a snippet fro ...

Ways to eliminate a specific Chip from Autocomplete outside of material UI

Seeking assistance with displaying selected values as <Chip /> outside of the <TextField /> in <Autocomplete />. The issue lies in deleting these chips and updating the selected prop within <Autocomplete />. Any suggestions or solut ...

How do I implement a dynamic input field in Angular 9 to retrieve data from a list or array?

I'm looking to extract all the strings from the Assignes array, which is a property of the Atm object, and populate dynamic input fields with each string. Users should be able to update or delete these strings individually. What approach can I take us ...

What could be causing the issues with SSL certificates when using Node.js/Express-TypeScript?

I'm currently in the process of transitioning a project's backend from JavaScript (Node.js/Express) to TypeScript. However, I've encountered an unusual issue where FS's readFileSync is unable to access the key.pem or cert.pem files in t ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Determine if each element in an array is present in the MongoDB document's array

Is it possible to determine whether a specific element exists within an array in a MongoDB document? For instance: If we have the following document { "_id": "A", "userId": "B", "selectedUsers": ["C", "D"] } and another array ["E", "C"]. ...

Disabling a specific dropdown within ng-repeat in AngularJS

I've encountered a problem with the ng-repeat in my HTML code: <div ng-repeat="a in items"> <div> <span>{{a.name}}</span> </div> <div> <select ng-model="a.c_id" ng-options="d.c_id as d.description ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...

What could be causing my processes to fail the second time using Vue?

In my Vue application, I have a parent component that contains several nested components. Initially, I retrieve product data from the database and perform calculations using Vue on the elements stored in an array. Everything works fine the first time, but ...

The Angular masonry directive is causing inner elements to disappear with an error message popping up: "Oh no! Masonry is

Having some difficulties implementing the Angular Masonry Directive by klederson in a project. The elements are taking up space in the body tag but not appearing visible, and an error message is being displayed in the console. Including the masonry depend ...

Use VB.NET to dynamically update cell content in HTML

Can you assist me with updating cellContent in HTML using vb.net? The DataGrid view is on a website. Below is the inspected HTML: <div class="grid-controls"> <form method="post" class="vss-app-form grid-control-popover none" id="gridMorePopov ...

`Cannot press when using custom cursor in JS?`

Hey there! I'm currently working on implementing a custom cursor for specific elements on my website. However, I've encountered a little hiccup - once the custom cursor is in place, I'm no longer able to click on any elements. Does anyone ha ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

Is it possible for multiple queries executed within a websql transaction to be run concurrently?

An informative tutorial online demonstrates the following transaction: db.transaction(function (tx) { tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")&ap ...

Sending data to Firebase Storage with AngularFire2

I've been working on a project involving Angular2 and Firebase, aiming to upload images to Firebase Storage. In order to achieve this, I created the Component with the constructor, function, and template. However, I am unsure about the correct way to ...

When the React application loads, loadingbar.js will be mounted initially. However, as the props or states are updated, the object

I recently made the switch from using progressbar.js to loadingBar.js in my React application for widget progress. Everything was working smoothly with progressbar.js, but once I switched to loadingBar.js, I encountered a strange issue. After the page load ...

Concealing Angular Flexslider until it is entirely loaded

I'm having trouble getting my angular flexslider to display images smoothly. Currently, the images take a moment to load and it doesn't look great. I'd like them to fade in once everything is fully loaded. How can I achieve this? I've t ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...