Struggling to modify a group of objects by incorporating a different group of objects

I have two separate sets of objects, storedArray is saved in my file system and inputArray is created from user input to update storedArray. Each array has a minimum length of 1 with no maximum limit. They may not necessarily be the same length. My goal is to iterate over each array and:

  1. If the name from inputArray matches the name in storedArray and the age is the same, then do nothing in storedArray but keep that object in storedArray (e.g., John).
  2. If the name from inputArray matches the name in storedArray but the age is different, update only the age value in the existing object in storedArray (e.g., Jane).
  3. If there is a new object in inputArray with a different name that doesn't match any names in storedArray, push the new object to storedArray (e.g., Morris).
  4. Must remove other objects in storedArray that do not match those in inputArray (e.g., Joanna, Jim).

Transform this:

const storedArray = [
        {"name": "John", "age": 25, "courses": 5},
        {"name": "Jane", "age": 21, "courses": 3},
        {"name": "Joanna", "age": 19, "courses": 2},
        {"name": "Jim", "age": 20, "courses": 4},
];

to this:

const storedArray = [
        {"name": "John", "age": 25, "courses": 5},
        {"name": "Jane", "age": 23, "courses": 3},
        {"name": "Morris", "age": 18, "courses": 0}
];

I attempted to achieve this using a for of loop but encountered 22 results, some of which were missing. Additionally, I tried pushing it into a new array. While similar posts exist on SO, their end goals differ from mine. Nonetheless, I tested their code without success.

This is what I have tried:

const storedArray = [
        {"name": "John", "age": 25, "courses": 5},
        {"name": "Jane", "age": 21, "courses": 3},
        {"name": "Joanna", "age": 19, "courses": 2},
        {"name": "Jim", "age": 20, "courses": 4}
];

const inputArray = [
        {"name": "Jane", "age": 23, "courses": 0},
        {"name": "John", "age": 25, "courses": 0},
        {"name": "Morris", "age": 18, "courses": 0}
];

let newArray = [];

for(let item of storedArray) {
    for(let each of inputArray) {
        if(item.name === each.name && item.age === each.age){
            newArray.push(item);
        }else if(item.name === each.name && item.age !== each.age) {
            item.age = each.age;
            newArray.push(item);
        }else if(item.name !== each.name){
            newArray.push(each);
            newArray.push(item);
        }
    }
}

console.log(newArray);

Answer №1

To locate the corresponding object in an array, you can utilize Array#reduce combined with Array#find. The process involves searching for matching elements based on a specific criterion within two separate arrays. If no match is found, the new element is added to the result array. Conversely, if a match is found, the age information is updated before insertion.

const storedArray = [
        {"name": "John", "age": 25, "courses": 5},
        {"name": "Jane", "age": 21, "courses": 3},
        {"name": "Joanna", "age": 19, "courses": 2},
        {"name": "Jim", "age": 20, "courses": 4},
];
const inputArray = [
        {"name": "Jane", "age": 23, "courses": 0},
        {"name": "John", "age": 25, "courses": 0},
        {"name": "Morris", "age": 18, "courses": 0}
];
const res = inputArray.reduce((acc,curr)=>{
    const stored = storedArray.find(({name})=>name===curr.name);
  if(stored){
    stored.age = curr.age;
    acc.push(stored);
  } else {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(res);

Answer №2

Instead of modifying the storedArray, focus on updating the inputArray.

Iterate through the inputArray and compare each object with the ones in the storedArray. If a match is found, update the course property of the current object and return it in each iteration.

const storedArray = [
  {"name": "John", "age": 25, "courses": 5},
  {"name": "Jane", "age": 21, "courses": 3},
  {"name": "Joanna", "age": 19, "courses": 2},
  {"name": "Jim", "age": 20, "courses": 4},
];

const inputArray = [
  {"name": "Jane", "age": 23, "courses": 0},
  {"name": "John", "age": 25, "courses": 0},
  {"name": "Morris", "age": 18, "courses": 0}
];

let updatedStoredArr = inputArray.map(a => {
  const exists = storedArray.find(b => a.name == b.name);

  if (exists) {
    a.courses = exists.courses;
  }

  return a;
});

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

You can enhance the code's conciseness by using a ternary operator along with the comma operator

let updatedStoredArr = inputArray.map(a => {
  const exists = storedArray.find(b => a.name == b.name);
  return exists ? (a.courses = exists.courses, a) : a;
});

Answer №3

Given that the rules dictate that the newArray will mimic the inputArray, with the exception of updating the courses based on values from storedArray, a simple solution to achieve this objective is as follows:

let newArray = inputArray.slice();

for(var i = newArray.length - 1; i >= 0; i--) {
  for(let stored of storedArray) {
    if(stored.name === newArray[i].name){
      newArray[i].courses = stored.courses;
    }
  }
}

[update]: Following the concise approach recommended by @Yousaf is the optimal course of action.

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

AngularJS encountered an error following a successful GET request

I'm attempting to retrieve data from the server using this code snippet. $scope.get_file_list = function() { delete $http.defaults.headers.common['X-Requested-With']; //We don't want OPTIONS but GET request $htt ...

How can I determine if text inside a tag is visible on a webpage using JavaScript or React?

As a beginner in programming, I am looking to verify if the h3 tag containing the text "hello" is present within the document. Let's examine the following HTML: <div class= "parent_div"> <div class="child_div"> <h3>hell ...

Can someone show me how to create an Array of Buttons using JavaScript? Also, I'm looking for guidance on how to generate random images using this code

Currently, I am working on creating a Memory Game. My main focus right now is setting the card images randomly, but for some reason, my code only displays the top image. var images = ["url(IMG1.jpg)","url(IMG2.jpg)"...]; var randomIMG =0; var card = "< ...

The assertion that 'd3Ctrl' is not a valid function, but instead is undefined

Although several people have raised the same issue before and I've attempted their solutions, I still can't seem to resolve it. My problem involves using d3, but I keep encountering this error: app.js var app = angular.module('myApp', ...

What is the best way to add a refresh link to my CAPTCHA script?

I have a captcha script that is functioning well. However, I am struggling to figure out how to implement a refresh function for it. Below is the code from verificationimage.php: <?php header('Content-type: image/jpeg'); $width = 50; $heig ...

How to customize the font size in three.js CSS3DRenderer

I am trying to use threejs's CSS3DRenderer to display text in my 3D view. However, I am facing issues with controlling the font size. Despite setting font-size: 1px in CSS, the text remains large. I also attempted to adjust the scale of the css3dobjec ...

Issue with the rendering of the Google Font "Playfair Display" involving the letters "ff" being displayed incorrectly

There seems to be a problem with the Google Font "Playfair Display" when two consecutive "f" characters are used. Check out this example of the odd rendering issue My idea for a fix involves creating a JavaScript function that scans all text on the websi ...

Utilize PHP server to serve index.html for all routes with the combination of React and react-router-dom

Usually, I develop websites using a combination of reactjs, node, and express, then deploy them to Heroku. Everything works smoothly with this setup. However, I recently received a request to create a reactjs frontend with a PHP backend and deploy it to c ...

jQuery TextExt - Trouble with setting the URL for Ajax autocomplete

Currently, I am utilizing the jQuery TextExt plugin for autocomplete. While using its example json url (data.json), everything functions as expected without any issues. However, when attempting to use my own custom url, similar to the one below: $('# ...

Is there a way to troubleshoot a webpack-compiled npm module effectively?

Looking to debug an npm module compiled with webpack by setting breakpoints and stepping through the code? The issue may arise when importing the module locally using npm link, as only the compiled code is accessible for debugging from the application. W ...

Harness the power of a NUXT component on a different website

Currently, I have a fully functional NUXT application that consists of numerous pages and components operating in `universal` mode. My challenge now is to render one of these components on a separate static HTML website. Exporting a component from a stand ...

Customize Bootstrap Vue dropdown without any predefined styling options

After reviewing the documentation, I created a sample example utilizing the b-dropdown component: You can view the example here: https://codesandbox.io/s/6lhk6?file=/src/components/GenericItem.vue However, when I implemented the component in the code: &l ...

Experience the moment when an item is dragged out of the menu

I have a collection of images in a menu that I can drag out and they will snap back using the Packery library <div id="menu"> <div class="img"> <Img src="..."/> </div> I am trying to figure out how t ...

The function `React.on('languageChanged')` is not effectively detecting changes in the language

I'm new to working with React and I'm looking for the best way to detect when a user changes their language preference. I am currently using next-translate to handle translations, but for some resources that come from an API, I need to update the ...

The equivalent of ESM for resolving modules using the `createRequire` function with a specified

In the process of developing a JavaScript instrumentation engine, I am currently focused on traversing a source file's Abstract Syntax Tree (AST) and queuing imported modules for instrumentation in a recursive manner. In order to achieve this, it is c ...

The onblur event is triggering prior to the value being updated

There are two input fields within a <form> element. I am trying to retrieve the value of one input field (dpFin) once it has been changed. The issue is that when I attempt to get the new value inside the event using var endDt = document.getElementByI ...

An Angular directive utilizing dual aliases

Is there a simple method to give a directive two distinct names? For example: app.directive(['directiveNameOne', 'directiveNameTwo'], function() {...}); I have created a directive that handles both radio buttons and checkboxes in th ...

Having trouble loading the JavaScript source file... somewhat frustrating

I am completely baffled by this situation. Completely bewildered. In the process of constructing an ad network framework, I primarily worked on Kodingen during the prototyping phase and everything functioned smoothly there. However, after shifting to a ne ...

Safari is currently unable to process XML responses

Here is the code we have attempted, please review and provide feedback. function GetXmlHttpObject() { var objXMLHttp=null; if (window.XMLHttpRequest) { objXMLHttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...