Replacing an object in an array based on a specific condition

I have a scenario where I need to update an array with values from another dynamic array. The key point to consider here is that the order or indices of the elements are not important and may not be sequential.

arrayA = [
{name: 'John Doe', sport: 'soccer', point: 20},
{name: 'Jack Kim', sport: 'tennis', point: 10},
{name: 'Tiger Wood', sport: 'golf', point: 22},
{name: 'Lewis Hamilton', sport: 'F1', point: 30},
]

The arrayB contains different point values and can vary in size.

arrayB = [
{name: 'John Doe', sport: 'soccer', point: 50},
{name: 'Jack Kim', sport: 'tennis', point: 100},

]

The resulting newArray will combine both arrays, updating values from arrayB if there's a match.

newArray = [
{name: 'John Doe', sport: 'soccer', point: 50},
{name: 'Jack Kim', sport: 'tennis', point: 100},
{name: 'Tiger Wood', sport: 'golf', point: 22},
{name: 'Lewis Hamilton', sport: 'F1', point: 30}]

I am seeking an optimal way to achieve this rather than my initial idea of using slice and push methods which might not be efficient.

NOTE: This is more of an algorithmic explanation and I'm open to suggestions on improving the approach.


let newArray = [];
arrayA.map(v => {
    if(v.sport === arrayB.sport) {
      index = arrayA.findIndex(v.sport)
      arrayA.slice(index);
       newArray = arrayA;
     }
});

newArray.push(arrayB)


Answer №1

To utilize the player's points from the second array if they exist, while falling back to the original points when not found, you could iterate over the first array:

const arrayA = [
{name: 'John Doe', sport: 'soccer', point: 20},
{name: 'Jack Kim', sport: 'tennis', point: 10},
{name: 'Tiger Wood', sport: 'golf', point: 22},
{name: 'Lewis Hamilton', sport: 'F1', point: 30},
]

const arrayB = [
{name: 'John Doe', sport: 'soccer', point: 50},
{name: 'Jack Kim', sport: 'tennis', point: 100},
]

const result = arrayA.map(({ name, sport, point }) => ({
    name, sport,
    point: arrayB.find((p) => p.name === name && p.sport === sport)?.point ?? point,
}));

console.log(result);

If certain syntax is unfamiliar, here are some resources for reference:

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

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

"Organizing data in a dynamic table using AJAX and JSON

Can you please provide a more detailed explanation? I recently started learning ajax and have a question about receiving and outputting JSON data from the server. {"JsonResult":[{"Name":"Иванов Иван Иванович" ...

Browse through the input file to find and display all unique struct names

#include <stdio.h> #include <string.h> #include <stdlib.h> /* This program searches and prints all unique struct names within an input file */ int main(int argc, char *argv[]) { char temp[64], buf[64], filename[128], array[1024] ...

Retrieving the data input from a datalist and using v-model will automatically reset the datalist

Looking for a way to preserve options in a datalist after selecting one using v-model in Vue. Currently, the selected option clears all other options due to two-way binding. Is there a method to only capture the selected value without removing the rest of ...

Can a sophisticated text editor be utilized without a content management system?

Many website builders utilize rich text editors as plugins to enhance content creation, such as in CMS platforms like Joomla and WordPress. However, can these same editors be easily integrated into a custom website built from scratch using just HTML, PHP ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Combining Jasmine 2.0's async done() with angular-mocks inject() in a single test case

Typically, my test cases are structured like this: it("should send get request", inject(function(someServices) { //some test })); However, for Jasmine 2.0 async tests, the format changes to: it("should send get request", function(done) { someA ...

Transform a JavaScript object into the appropriate REST query format using the Meteor.call() function

In my attempt to make an API call to a Wordpress REST API, I came across different ways of doing so. The console version of the call looks like this: http://dev.thomastraum.com/wp-json/posts?type=tt_works&filter[work_categories]=all&filter[posts_p ...

The local storage is unavailable on Chrome Mobile due to null value being

My error reporting system is detecting issues with JS Web Storage failures specifically on Android devices using Chrome mobile. Interestingly, I have not been able to replicate this error on my own Android device. The error message that keeps popping up i ...

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 ...

Is it possible to trigger an event for only one connected client instead of broadcasting it to all clients using socket.io?

I am seeking a way to send an event to just one connected client, rather than broadcasting it to all clients using io.emit(). ...

Value Error: the decimal value provided is not valid (parameter="value", value="[object Object]", code=INVALID_ARGUMENT, version=bignumber/5.7.0)

Struggling to develop a function that updates the price of an NFT. Unfortunately, encountering this error: Error: invalid decimal value (argument="value", value="[object Object]", code=INVALID_ARGUMENT, version=bignumber/5.7.0) Here& ...

You cannot convert a function to a string while utilizing axios get in nuxtServerInit

While attempting to connect my app to the backend using Udemy's Nuxt.js course, I encountered a GET http://localhost:3000/ 500 (Internal Server Error) on the client side with the following code: import Vuex from 'vuex'; import axios from &a ...

Export information from variables, lists, and dictionaries to a csv file

I am in the process of generating a csv file containing user information. So far, I have successfully created a csv file for variables like "name," "surname," and age. However, I also have data stored in lists and dictionaries with unknown lengths that I d ...

How can I use JSON path to extract all the elements within an array from a JSON input?

I want to extract all fields from a JSON array and turn it into a flat JSON file. Here is an example of the input: Array JSON input: { "field1": "ALNT12345", "field2": "ALNT345346", "field3": "2015353423", "field4": "2332124343", "arr ...

Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string. Suppose I have two checkboxes labeled: label1 and label2, my a ...

when webpack loads the bundle.js file, the mime type is converted to text/html

I'm currently working on implementing server side rendering for an application using react-redux and express for the server. We are also utilizing webpack to bundle our assets. To get started, I referred to the following documentation: https://redux ...

An approach to transferring the ID of a multiple dropdown within the $.each function

function filterFields(classname, value, chkClass) { var checkedfields = []; $.each($("."+classname+" option:selected"), function(){ checkedfields.push($(this).val()); }); $('#'+chkClass+'Filters').val(ch ...

What could be the issue with my injection supplier?

When running the following code, the configuration works fine, but an error is returned: Uncaught Error: [$injector:unpr] Unknown provider: AngularyticsConsoleHandlerProvider <- AngularyticsConsoleHandler <- Angularytics Code snippet: angular.modu ...

php failure to execute included file

Hey there! I'm currently facing an issue with including a file that contains all of my 'head' information. My goal is to simplify and streamline my page by breaking it down. In my index.php file, here's what I did: <?php include & ...