Comparing elements within one array to those in another array

I am working with two arrays containing different data sets

array1 = [{id:"1",title:"Writing"},{id:"2",title:"Singing"},{id:"3",title:"Dance"}];

array2 = [{tags: "1",title: "USA",type: "text"},
{tags: "1,2,3",title: "Japan",type: "image"},
{tags: "2,3",title: "Japan",type: "image"}];

My task is to link the id values from array1 to the tags values in array2 and display the corresponding titles from array1.

As a result, the updated array2 should appear like this:

array2=[{tags:"Writing",title:"USA", type:"text"},
{tags: "Writing,Singing,Dance",title: "Japan",type: "image"},
{tags: "Singing,Dance",title: "Japan",type: "image"}];

I managed to map the array1 data, but I encountered difficulties beyond that point.

var newtags= (array1).map(obj=>{
var rObj={};
rObj[obj.id]=obj.title;
return rObj;
});

Answer №1

To create a mapping object with each unique id as a key and its corresponding title as the value, you can utilize the reduce method. Next, iterate over array2 and utilize the split method on each tags element to extract new tags.

const array1=[{id:"1",title:"Writing"},{id:"2",title:"Singing"},{id:"3",title:"Dance"}],
      array2=[{tags:"1",title:"USA",type:"text"},{tags:"1,2,3",title:"Japan",type:"image"},{tags:"2,3",title:"Japan",type:"image"}]

const map = array1.reduce((res, { id, title }) => ({ ...res, [id]: title }), {});

const output = array2.map(({ tags, ...rest }) => {
  const newTags = tags.split(',').map(id => map[id]).join(',');
  return { tags: newTags, ...rest };
});

console.log(output)

You can also generate the mapping object using Object.fromEntries()

const map = Object.fromEntries(array1.map(({ id, title }) => [id, title]));

Then employ the regex pattern /\d+(?=,|$)/ to identify the numbers and substitute them with their corresponding titles

const array1=[{id:"1",title:"Writing"},{id:"2",title:"Singing"},{id:"3",title:"Dance"}],
      array2=[{tags:"1",title:"USA",type:"text"},{tags:"1,2,3",title:"Japan",type:"image"},{tags:"2,3",title:"Japan",type:"image"}]

const map = Object.fromEntries(array1.map(({ id, title }) => [id, title]));

const output = array2.map(({ tags, ...rest }) => {
  const newTags = tags.replace(/\d+(?=,|$)/g, num => map[num]);
  return { tags: newTags, ...rest };
});

console.log(output)

Answer №2

Here is the solution

To combine array1 and array2, I am utilizing .map, .reduce, and .replace methods.

const array1 = [
    {
        id: "1",
        title: "Writing"
    },
    {
        id: "2",
        title: "Singing"
    },
    {
        id: "3",
        title: "Dance"
    }
]

const array2 = [
    {
        tags: "1",
        title: "USA",
        type: "text"
    },
    {
        tags: "1,2,3",
        title: "Japan",
        type: "image"
    },
    {
        tags: "2,3",
        title: "Japan",
        type: "image"
    }
]

const array3 = 
  array2.map(item => ({ 
    ...item,
    tags: array1.reduce((tags, {id, title}) => tags.replace(id, title), item.tags),
  }))
  
console.log(array3)

Answer №3

Here is a suggested approach:

  • Utilize Array.reduce method to transform array1 into an object where id becomes the key and title becomes the value (Step 1)
  • Traverse through array2 with Array.forEach to update its tags property
    • For updating the tags property, start by splitting it by , to convert it to an array
    • Map each value in the array to its corresponding value in the Object created in step 1
    • Join the array back with , and assign it back to tags

let array1 = [{id:"1",title:"Writing"},{id:"2",title:"Singing"},{id:"3",title:"Dance"}];
let array2 = [{tags: "1",title: "USA",type: "text"},{tags: "1,2,3",title: "Japan",type: "image"},{tags: "2,3",title: "Japan",type: "image"}];

let obj = array1.reduce((a,c) => Object.assign(a, {[c.id] : c.title}), {}); 
array2.forEach(o => o.tags = o.tags.split(",").map(v => obj[v]).join(","));

console.log(array2);

Answer №4

In order to achieve the desired outcome, follow the steps below to loop through array1 and replace array2 tags with their corresponding titles:

  1. Utilize the forEach method to loop through Array1
  2. Replace array2 tags with the title of each array1 item based on the array id

array1 = [{id:"1",title:"Writing"},{id:"2",title:"Singing"},{id:"3",title:"Dance"}];

array2 = [{tags: "1",title: "USA",type: "text"},
{tags: "1,2,3",title: "Japan",type: "image"},
{tags: "2,3",title: "Japan",type: "image"}];

array1.forEach(v =>{
const re = new RegExp(v.id, "g");
array2 = JSON.parse(JSON.stringify(array2).replace(re, v.title))
})

console.log(array2);

Answer №5

One approach could be to break this task into smaller, reusable functions. While it may seem like over-engineering at first, encountering similar questions frequently suggests a need to focus on foundational concepts.

To achieve our goal of looking up values in an array with potentially arbitrary field names, we can create a function called makeDictionary. This function will take field names and the array as input, returning an object that maps them accordingly, for example {'1': 'Writing', '2': 'Singing',...}.

Next, we can use the fillField function by providing a dictionary, field name, and an object to replace that field with values from the dictionary lookup. This function is more tailored to the specific issue, especially given the complexity introduced by the comma-separated string format for tags.

After defining these functions, we can easily implement useTags, which directly addresses your requirements. By using field names id and title for the dictionary and tags for main objects, we can streamline the process.

Here is the merged version of these functions:

const makeDictionary = (keyName, valName) => (arr) => 
  arr .reduce 
    ( (a, {[keyName]: k, [valName]: v}) => ({...a, [k]: v}) 
    , {} 
    )

const fillField = (field, dict) => ({[field]: f, ...rest}) => ({
  ...rest,
  [field]: f .split (/,\s*/) .map (t => dict[t]) .join (', ')
})


const useTags = (tags, dict = makeDictionary ('id', 'title') (tags) ) =>
  (objs) => objs .map ( fillField ('tags', dict) )


const tags = [{id: "1", title: "Writing"}, {id: "2", title: "Singing"}, {id: "3", title: "Dance"}];

const updateTags = useTags (tags) 

const items = [{tags: "1", title: "USA", type: "text"}, {tags: "1, 2, 3", title: "Japan", type: "image"}, {tags: "2, 3", title: "Japan", type: "image"}];

console .log (
  updateTags (items)
)

Note that some formatting adjustments were made to the tags like tags: "2,3" and tags: "Singing,Dance", but these can be easily reverted. Ideally, transitioning to using arrays for tags would streamline the process further.

Answer №6

To convert an array using a JavaScript Map, you can assign new values to objects based on the mapping.

var array1 = [{ id: "1", title: "Writing" }, { id: "2", title: "Singing" }, { id: "3", title: "Dance" }],
    array2 = [{ tags: "1", title: "USA", type: "text" }, { tags: "1,2,3", title: "Japan", type: "image" }, { tags: "2,3", title: "Japan", type: "image" }],
    tags = array1.reduce((m, { id, title }) => m.set(id, title), new Map),
    result = array2.map(o => ({ ...o, tags: o.tags.split(',').map(Map.prototype.get, tags).join() }));

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

Answer №7

To manipulate data in JavaScript, leverage the filter, map, and join methods. Initially, split the tags and then proceed to filter them within array1.

var newtags= (array2).map(obj=>{
   let tags = obj.tags.split(",");
   let titles = array1.filter(c=>tags.includes(c.id)).map(c=>c.title);
   obj.tags = titles.join();
   return obj;
});

array1 = [{id:"1",title:"Writing"},{id:"2",title:"Singing"},{id:"3",title:"Dance"}];

array2 = [{tags: "1",title: "USA",type: "text"},
{tags: "1,2,3",title: "Japan",type: "image"},
{tags: "2,3",title: "Japan",type: "image"}];

var newtags= (array2).map(obj=>{
let tags = obj.tags.split(",");
let titles = array1.filter(c=>tags.includes(c.id)).map(c=>c.title);
obj.tags = titles.join();
return obj;
});
console.log(newtags);

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

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

The function _path2.default.basename does not work when using convertapi within an Angular framework

I'm currently working on integrating the convertapi into my Angular 11 application by referencing the following documentation https://www.npmjs.com/package/convertapi My goal is to convert PDFs into images, However, I encountered an issue when tryi ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

What causes the error of inputRef.current being null in CurrencyTextField?

When attempting to target the second 'CurrentTextField' after changing the value of the first 'CurrentTextField', an error occurs stating 'inputRef.current is null'. import React, {useRef } from 'react'; import Curr ...

Buttons in Laravel are shifting unexpectedly

There are three buttons available with different functions. <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary"> {{ __('update') ...

Pressing the shortcut key will activate the function specified in ng-click,

I have been searching for a solution to my problem, but I haven't found anything that really helps. What I am looking for is a shortcut within an ng-click directive where there is only an if condition without an else expression. Essentially, I just wa ...

Vue.js: EventBus.$on is not properly transmitting the received value

I recently started working with Vue and am currently exploring the best way to organize my event bus. In my project, I have a main layout view (Main.vue) that includes a router view where I pass emitted information from a child component like this: <te ...

Repeated attempts to initiate ajax script failing to function

I am completely new to the world of Ajax, having just started learning about it a few days ago. Despite my lack of experience, I need to incorporate it into a form that I am creating for my employer. Unfortunately, I have been facing difficulties in getti ...

Issue with the back-to-top button arises when smooth-scrolling feature is activated

This Back To Top Button code that I discovered online is quite effective on my website. // Defining a variable for the button element. const scrollToTopButton = document.getElementById('js-top'); // Creating a function to display our scroll-to- ...

The CSS is not displaying correctly on Safari and Chrome browsers in Mac OS

I'm having trouble with CSS not loading properly on Apple devices for a website I made. Despite maintaining all media query statements and style sheets separately, the display is not correct in MAC OS safari and chrome. However, everything looks fine ...

How can I keep the cursor in place while editing a phone number field on Sencha ExtJS?

After one backspace move, the cursor on the phone number field automatically moves to the end which can be inconvenient if the user only wants to edit the area code. Unfortunately, I am unable to post images at the moment due to insufficient reputation. B ...

How can I identify the correct key to access a specific value within an array?

I have an array of data that looks like this, and I need to store the 'sale' value in the database only if the currency is set to USD. foreach ($cur_array as $curs) { print_r ($curs)."<br>"; if ($curs['currency'] = "USD") ...

Utilize the dimensions of one image to resize others using the JavaScript method .getBoundingClientRect

I am attempting to transfer the width and height measurements of the initial image to all subsequent images on the page. Currently, I have successfully applied the dimensions of the first image to the second one, but I am facing difficulties with the thir ...

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

Locate a specific word within a sentence using PHP

Here is a snippet of code I am struggling with: $newalt = "My name is Marie"; I need to check if the words 'marie' or 'josh' appear in the above sentence: $words = array("marie", "josh"); $url_string = explode(" ", $newalt); if (!i ...

Is Jquery Mobile's Table lacking responsiveness?

I have implemented a basic table from the jQuery Mobile website on my page. Take a look at the HTML code below: <div data-role="page" id="mainPage"> <div data-role="content> <table data-role="table" id="my-table" da ...

Issue encountered: "require" is not recognized when attempting to access my local JSON file in Vue.js

I am venturing into the world of vuejs... I attempted to retrieve data from my JSON file stored locally, but the decision on which specific JSON file's data to fetch is dynamic. I keep encountering an error stating 'require' is not define ...

Determining html column values using a related column and user input

Is there a way to populate an HTML table column (using Javascript or jQuery) based on the values in another column and an input field? For instance, if I input the number 115 into the field, then the advance column should display a value of 1 for each ath ...

What is the best method for creating table column text within a Bootstrap Modal through JSON data?

I am currently working on creating a table by using key value pairs from a JSON object. The keys will represent column-1 and the values will correspond to column-2. The desired output can be viewed at this link. I am wondering if there is a standard method ...