Analyzing and inserting elements into an array of objects

The following code aims to:

1) iterate through the two arrays,

2) if an item exists in both arrays, add its value to the value of the matching item in the first array,

3) if the item is found in arr2 but not in arr1, add the item to arr1. The code functions correctly when both arrays are the same size, but encounters issues when dealing with arrays of different sizes.

Current Result:

[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [6, "mugs"], [2, "Dirty Sock"], [3, "rags"]]

Expected Result:

[[42, "Bowling Ball"], [4, "Dirty Sock"], [2, "cat"], [3, "rags"], [3, "mugs"]]

Here is the code snippet:

function updateInventory(arr1, arr2) {
  for (var i = 0; i < arr1.length; i++) {
    for (var j = i; j < arr2.length; j++) {
      if (arr1[i][1] === arr2[j][1]) {
        arr1[i][0] += arr2[j][0];
      }
      if (arr1[i].indexOf(arr2[j][1]) === -1) {
        arr1.push(arr2[j]);
      }
      if (arr2.length > arr1.length) {
        arr1.push(arr2[arr2.length - 1]);
      }
      else
        break;
    }
  }
  return arr1;
}

var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [2, "cat"],
];

var newInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [3, "rags"],
    [3, "mugs"]
];

updateInventory(curInv, newInv);

What seems to be the issue in this code snippet?

Answer №1

To efficiently manage your inventory, consider utilizing a hash table to compare and update the currInv data.

let curInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [2, "cat"]],
    newInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [3, "rags"], [3, "mugs"]],
    inventory = Object.create(null);

curInv.forEach(function (a) {
    this[a[1]] = a;
}, inventory);

newInv.forEach(function (a) {
    if (!this[a[1]]) {
        this[a[1]] = [0, a[1]];
        curInv.push(this[a[1]]);
    }
    this[a[1]][0] += a[0];
}, inventory);

console.log(curInv);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Perhaps you are making things more complex than necessary. Here's a functional code snippet.

function mergeInventory(currentInventory, newInventory) {
  for (var i = 0; i < newInventory.length; i++) {
    var foundMatch = false;
    for (var j = 0; j < currentInventory.length; j++) {
      if (currentInventory[j][1] === newInventory[i][1]) {
        currentInventory[j][0] += newInventory[i][0];
        foundMatch = true;
      }
    }

    if (!foundMatch) {
      currentInventory.push(newInventory[i]);
    }
  }
  return currentInventory;
}


var currentInv = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [2, "cat"],
];

var additionalInv = [
  [21, "Bowling Ball"],
  [2, "Dirty Sock"],
  [3, "rags"],
  [3, "mugs"]
];

console.log(mergeInventory(currentInv, additionalInv));

Functionality Details

  1. Iterate through all items in newInventory.
  2. Check each item against the existing currentInventory.
  3. If a match is found, increment the quantity in currentInventory by that in newInventory.
  4. If no match is found, add the item from newInventory to currentInventory.

Answer №3

When dealing with arrays, you have the option to either merge them or combine them to achieve the desired outcome automatically.

var array3 = curInv.concat(newInv);

If you are looking to identify the unique elements within the arrays

// Merges both arrays and finds the unique items var array3 = **

arrayUnique(array1.concat(array2));

function arrayUnique(array) {
   var a = array.concat(); 
   for(var i=0; i<a.length; ++i) { 
          for(var j=i+1; j<a.length; ++j) {
             if(a[i] === a[j]) a.splice(j--, 1); } 
     } 
   return a; 
}

**

Answer №4

In this solution, a concise implementation using a hash (implemented as a Map) is presented following a functional programming style:

function updateInventory(currentInventory, newInventory) {
    return Array.from(
        newInventory.reduce( (map, [quantity, item]) => map.set(item, (map.get(item) || 0) + quantity),
                   new Map(currentInventory.map ( ([quantity, item]) => [item, quantity] )) ), // swap pairs
        ([item, quantity]) => [quantity, item]) // swap back afterwards;
}

// Sample data
var currentInventory = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [2, "cat"],
];

var newInventory = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [3, "rags"],
    [3, "mugs"]
];

// calling the function
currentInventory = updateInventory(currentInventory, newInventory);
// Output the result
console.log(currentInventory);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If the data had pairs where the item name comes first and quantity second, the code would have been much shorter. This is due to how Map objects are initialized with key-value pairs, not value-key pairs:

function updateInventory(currentInventory, newInventory) {
    return [...newInventory.reduce( (map, [quantity, item]) => map.set(item, (map.get(item) || 0) + quantity), new Map(currentInventory) )];
}

// Sample data
var currentInventory = [
    ["Bowling Ball", 21],
    ["Dirty Sock", 2],
    ["cat", 2],
];

var newInventory = [
    ["Bowling Ball", 21],
    ["Dirty Sock", 2],
    ["rags", 2],
    ["mugs", 2]
];

// calling the function
currentInventory = updateInventory(currentInventory, newInventory);
// Output the result
console.log(currentInventory);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Since this function returns the result without mutating the input arguments, it is named updateInventory.

Improvements for the original code

  1. The outer loop should iterate over the second array for practicality in identifying missing elements in the first array.

  2. The inner loop should start at index 0 rather than the current position of the outer loop.

  3. When a match is found, there is no need to continue looping, so the inner loop should be exited.

  4. The section of code looking for matches should be outside the inner loop and corrected to prevent duplicates.

  5. Eliminate unnecessary break statements in the loops to prevent missing matches and duplicates.

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

Ditch the if-else ladder approach and instead, opt for implementing a strategic design

I am currently working on implementing a strategic design pattern. Here is a simple if-else ladder that I have: if(dataKeyinresponse === 'year') { bsd = new Date(moment(new Date(item['key'])).startOf('year&apos ...

AJAX brings back the previous value from an array

I am currently working on a website that will showcase various artwork. The concept involves using JavaScript to run a php file when the page loads, which in turn queries the server for the names and IDs of the image files (artwork.jpg) and displays them a ...

What are the methods to alter validation for a Formfield based on the input from other Formfields?

My aim is to create a Form where input fields are required only if one or more of them are filled out. If none of the fields have been filled, then no field should be mandatory. I came across a suggestion on a website that recommended using "valueChanges" ...

React TextField is not accommodating the new line character ' ' causing recognition issues

Explanation I have encountered an issue while using Material UI TextField and mapping through an array of objects fetched from a MongoDB database. Here is the code snippet in question: {state.map((item) => ( <TextField name=" ...

Split the string in JavaScript and then count the characters to decrypt

I am currently working on a task that involves splitting a string at every space. I have successfully achieved this using .split(" "), but now I need to determine the length of each individual string. My goal is to check if a given string includes a midd ...

Searching for all occurrences of a user-specified search term within a string array using C++

I'm currently working on an assignment that involves loading a file containing books and their authors in sequential lines. I have successfully loaded the book titles into a book title array and the authors into a book author array. Here are the task ...

jQuery Accordian malfunctioning for all elements except the first one in the list

Trying to implement an accordion feature that can be utilized across the entire website. The current logic seems to be partially functional... When I click on any of the accordions, it should open by adding a 'show' class, but this only works for ...

How can you selectively export a single function from a JavaScript file?

Within my project, I have two separate modules - one written in ts and the other in js. There is a utility within the js module that needs to be accessed by the ts module. The utility service.js looks like this: module.exports = { helloFriends: functi ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

"Want to learn how to dynamically disable an input field in AngularJS when another field is selected? Find out how to achieve this using the

Hey there, I'm dealing with two input fields. Input field A is a drop-down menu and input field B. They both have the same value (same ng-model). My goal is to clear the second input field whenever the user selects an option from the dropdown. Can any ...

The android application experiences crashing issues when utilizing the position or zIndex style properties within a react-native environment

In my code, I am attempting to display a semi-transparent black screen over my page in order to show a message or prompt in the center. I have tried using zIndex or elevation with position:'fixed' or position:'obsolet', and it works per ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Ways to conceal images until AFTER the completion of the jquery flexslider loading process

After trying to integrate wootheme's Flexslider on my website, I encountered a small issue with its loading process. Whenever the page is refreshed with the slider, there is a brief moment (approximately 1 second) where the first slide appears overly ...

Stop and start an Express.js server using the original port number

Currently, my Node.js application utilizes Express.js to handle incoming connections. The code snippet looks something like this: const express = require("express"); var server = express(); server.get("/test", (req, res) => testResponse(req, res)); ser ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Unable to load the node modules

In my development journey, I created an ASP.NET MVC project using Angular 2 in Visual Studio 2017 and set up node for package management. Here is a snippet from the package.json file: { "version": "1.0.0", "name": "asp.net", "private": true, ... ...

Encountering invalid parameters while attempting to utilize the track.scrobble service from the Last.Fm API in a Node.js application

After successfully completing the Last.Fm authentication process following the instructions provided here, I received the session key without any issues. However, my attempts to make an authenticated POST request to the track.scrobble method of the Last.Fm ...

Set a click listener on a button within Ext.window.MessageBox

Currently, I am dynamically generating a message box using Ext.window.MessageBox. var msgBox = Ext.create('Ext.window.MessageBox', { title: '', //message in window msg: 'message text', icon: ' ...

Gulp Watch fails to identify changes in the SASS SCSS directory

After setting up Gulp to compile SCSS into CSS using NanoCSS and gulp-css for the first time, I encountered an issue. While my do-sass command successfully compiles SCSS and minifies CSS files, it does not run when placed within a watch task. Any changes ...

Using Jquery to encase an element in a div while scrolling down and removing it while scrolling up

After some experimentation, I've managed to wrap an element inside a div using jQuery. My next challenge is to wrap it as you scroll down and unwrap it as you scroll up. Do you think this is achievable? Although I have succeeded in wrapping it while ...