What is the best way to correlate two arrays of strings with one another?

I am working with two sets of data:

First Set:

let training = [
  "Z1,1545 John Doe,P1",
  "Z2,2415 Shane Yu,P2"
];

Second Set:

let skill = [
  "P1, Shooting",
  "P2, Passing",
];

I need to combine both arrays based on their P number and exclude the P from the training array.

Expected Result:

[ 
  'Z1,1545 John Doe, P1, Shooting',
  'Z2,2415 Shane Yu, P2, Passing'
]

Is there a method to achieve this using ES6?

Answer №1

To create a customized mapping using ES6, you can utilize the Map function in JavaScript. By mapping each P<number> to a specific skill from your skill array, you can then easily manipulate your training array using .map() and .replace() methods to achieve your desired outcome:

const training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ];
const skill = [ "P1, Shooting", "P2, Passing", ];

const lookup = new Map(skill.map(item => [item.split(", ").shift(), item]));
const result = training.map(str => str.replace(/P\d+/, m => lookup.get(m)));
console.log(result);

If you prefer a simpler approach, you can opt for a linear search method using .find() and .startsWith() within the replace function. Keep in mind that this method may be less efficient, especially with a larger skills array (resulting in O(NK) complexity as opposed to the O(N+K) mentioned above):

const training = [ "Z1,1545 John Doe,P1", "Z2,2415 Shane Yu,P2" ];
const skills = [ "P1, Shooting", "P2, Passing"];

const result = training.map(str => str.replace(/P\d+/, m => skills.find(
  skill => skill.startsWith(m)
)));
console.log(result);

Answer №2

There is a possibility to convert the skill array into a Map object:

let skillMap = new Map(skill.map(e=>e.split(“,”)))

// By using split(“,”), we convert "P1, Shooting" into [“P1”,” Shooting”]
// The skill.map function creates a new array with the converted elements
// Each pair is used to create a key-value pair in the Map object

Subsequently, it is feasible to loop through the training array and retrieve the skill descriptions from skillMap. Here's a potential way to do it:

let output = training.map(e=>e.split(“,”)).map(e=>[e[0],e[1],e[2]+skillMap.get(e[2])]

Answer №3

Here's a slightly different strategy to solve the problem:

let playersInfo = [
    "Z1,1545 John Doe,P1",
    "Z2,2415 Shane Yu,P2"
];

let playerSkills = [
    "P1, Shooting",
    "P2, Passing",
];

let mergedData = playersInfo.map((player) => {
  const [, , playerIndex] = player.split(',');
  const playerSkill = playerSkills.find((skill) => skill.startsWith(playerIndex));
  
  return `${player}${playerSkill.slice(2)}`;
});

console.log(mergedData)

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

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

The ng-repeat function in AngularJs does not display the data despite receiving a successful 200 response

As part of my academic assignment, I am exploring Angularjs for the first time to display data on a webpage. Despite receiving a successful http response code 200 in the Chrome console indicating that the data is retrieved, I am facing issues with displayi ...

Getting rid of mysterious Google Analytics script from WordPress

My client has requested that I incorporate Google Analytics into her website. After accessing her Google account, I attempted to paste the tracking code into the appropriate section of the Wordpress plugin. To my surprise, the code did not work as expect ...

Determine the originating component in React by identifying the caller

Can you explain how to access the calling component in a React application? function MyCallingComponent() { return <MyReadingComponent/> } function MyReadingComponent() { console.log(callingComponent.state) } ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

The login form using Ajax and PHP is experiencing an issue where the response is consistently empty

I am having issues with my login form. Every time I enter a login and password, whether correct or incorrect, the JavaScript script returns an error and the "response" is empty when I try to print it. Can anyone offer assistance? $(document).ready(funct ...

When I try to use the mongoose find() function, I am receiving a Promise status of <Pending>

I recently developed a function to retrieve the list of all products stored in MongoDB using mongoose. However, when trying to log this information, I am unexpectedly getting a Promise instead. Below is the relevant code snippet: router.get('/', ...

Guide on linking a textarea with a boolean value in the child component

I have created a form component consisting of two components. The first component looks like this: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-ce ...

Integrate JavaScript into your HTML code

I'm a beginner in HTML and am working on creating a login form. Here is the code that I have written so far. I need help with importing my JavaScript code into the HTML form. C:\Program Files\xampp\htdocs\forsiteSystem\thems& ...

Starting a new React project

prtScn I'm encountering an issue while trying to initiate a new react app in Visual Studio Code. I have been following the given instructions as follows: in the visual code terminal : create-react-app sali (sali is the name) npm install node node_m ...

ASP.NET page experiences issues with executing Javascript or jQuery code

Having trouble with client scripts not functioning correctly on a child page that utilizes a master page. Looking for help to resolve this issue. <%@ Page Title="" Language="C#" MasterPageFile="~/Store.Master" AutoEventWireup="true" CodeBehind="NewSt ...

best method to pass byte array to ListBlockingQueue

Given that I am handling an array of bytes passed to me, not by choice but out of necessity. My task is to transfer the data to a LinkedBlockingQueue and ultimately iterate through the bytes to construct one or multiple XML messages (which may potentially ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

How can I insert an HTML/PHP code snippet into a <ul> list using JavaScript?

My upload.php file saves images into an uploads/ folder within my main directory. I am looking to dynamically add a new li tag to my index file each time an image successfully uploads. Here is a snippet from index.php: <ul> <li><im ...

Steps to Activate a Hyperlink for Opening a Modal Dialogue Box and Allowing it to Open in a New Tab Simultaneously

I am currently working on a website project. Within the website, there is a hyperlink labeled "View Page". The intention is for this link to open the linked page in a modal dialog upon being clicked. Below is the code snippet that I have used to achieve t ...

I've received an array of objects, but I require the objects to be consolidated into a single array using a MongoDB query

Hello, I am a newcomer to mongodb and I am attempting to generate a specific output using the mongodb aggregate function. I am aiming for a unified array of objects rather than multiple arrays of objects. Can someone assist me in achieving this desired out ...

Linking asynchronous functions does not function properly

I've been attempting to link two asynchronous functions together, but it appears that the second function is running before the first one. Below is the code snippet: function performAction(e) { const ZIP = document.getElementById('zip').valu ...

Validation for prototype malfunctioning

I am currently using Prototype.js to implement form validation on my website. One of the fields requires an ajax request to a PHP file for validation purposes. The PHP file will return '1' if the value is valid and '0' if it is not. Des ...

Mobile Drag and Drop with JavaScript

While experimenting with a user interface I created, I utilized jQuery UI's draggable, droppable, and sortable features. However, I observed that the drag and drop functionality does not work in mobile browsers. It seems like events are triggered diff ...