Contrast the identification numbers in a matrix with the identification numbers in a separate matrix

Today, we will be exploring how to group arrays of objects in JavaScript by ID. In this scenario, we have an array of IDs nested in an object of arrays (item3) that will be compared with another array of objects.

var existingArray = [
    {
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0200","0300"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0100","0300"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0100"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0300"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0200", "0100"],
      "item4": "blah4",
      "item5": "blah5"
    }
]

We now introduce our beloved DATA2 array which holds valuable information that we want to extract, specifically the "CandidateName" if the "relatedId" matches any of the IDs in item3 within EXISTINGARRAY.

var data2 = [
    {"CandidateName": "Mary", "relatedId": ["0100", "0200"]},
    { "CandidateName": "John", "relatedId": ["0200"]},
    { "CandidateName":"Peter", "relatedId": ["0300", "0100"]},
    { "CandidateName": "Paul", "relatedId": ["0300"]}
];

The goal here is to search for matching IDs between data2[i].relatedId[j] and existingArray[k].item3[l], then extract the corresponding "CandidateName" and append it to EXISTINGARRAY. The end result should resemble the following:

existingArray = [
    {
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0200","0300"],
      "item4": "blah4",
      "item5": "blah5",
      "item6": ["Mary", "Jonh", "Peter", "Paul"]
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0100","0300"],
      "item4": "blah4",
      "item5": "blah5",
      "item6": ["Mary", "Peter", "Paul"]
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0100"],
      "item4": "blah4",
      "item5": "blah5",
      "item6": ["Mary", "Peter"]
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0300"],
      "item4": "blah4",
      "item5": "blah5",
      "item6": ["Peter", "Paul"]
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0200", "0100"],
      "item4": "blah4",
      "item5": "blah5",
      "item6": ["Mary", "John","Peter"]
    }
]

Answer №1

We can solve this using ES6 by following the code snippet below:

existingArray.forEach( function (obj) {
    obj.item6 = [...new Set(obj.item3.reduce( (acc, id) => acc.concat(this.get(id)), [] ))]
}, data2.reduce (
    (acc, obj) => obj.relatedId.reduce (
        (acc, id) => acc.set(id, (acc.get(id) || []).concat(obj.CandidateName)), acc
    ), new Map()
));

var existingArray = [
    {
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0200","0300"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0100","0300"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0100"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0300"],
      "item4": "blah4",
      "item5": "blah5"
    },{
      "item1": "Blah1",
      "item2": "blah2",
      "item3": ["0200", "0100"],
      "item4": "blah4",
      "item5": "blah5"
    }
]

var data2 = [
    {"CandidateName": "Mary", "relatedId": ["0100", "0200"]},
    { "CandidateName": "John", "relatedId": ["0200"]},
    { "CandidateName":"Peter", "relatedId": ["0300", "0100"]},
    { "CandidateName": "Paul", "relatedId": ["0300"]}
];

existingArray.forEach( function (obj) {
    obj.item6 = [...new Set(obj.item3.reduce( (acc, id) => acc.concat(this.get(id)), [] ))]
}, data2.reduce (
    (acc, obj) => obj.relatedId.reduce (
        (acc, id) => acc.set(id, (acc.get(id) || []).concat(obj.CandidateName)), acc
    ), new Map()
));

console.log(existingArray);

Detailed Explanation

The code starts with creating an empty Map:

new Map()

This map is used as the accumulator (acc) while iterating over data2 array using reduce:

data2.reduce

Nested reduce operations allow iteration over each relatedId. If the accumulated value (acc) doesn't contain the id yet, a new array is created:

acc.get(id) || []

If the id already exists in the map, its corresponding array is used. Candidate name is then appended to it:

.concat(obj.CandidateName)

This updated array is set back into acc for the key id:

acc.set(id, ...)

The set method returns acc, which works well with reduce as it needs the return value for further accumulation.

The result of outer reduce call is a Map keyed by all ids from data2, with corresponding arrays of names.

This resulting map is passed as the second argument to forEach, becoming the reference for this. So when you see:

this.get(id)

it fetches the candidate name array for id from the map.

In the forEach callback, another reduce operates on item3 values:

obj.item3.reduce

An array of names accumulates and is then converted to a unique set using Set:

new Set(...)

The set is spread back into an array to remove duplicates:

[...new Set()]

This procedure assigns values to all item6 properties.

Answer №2

To add item6 to the existingArray, you can loop through it and use the map() function. To create the array containing item6, first utilize filter() and some() to filter objects with related values in their relatedId matching the current object's item3 in the existingArray. Then, simply use map() to retrieve only the names and return the object.

var existingArray = [{"item1":"Blah1","item2":"blah2","item3":["0200","0300"],"item4":"blah4","item5":"blah5"},{"item1":"Blah1","item2":"blah2","item3":["0100","0300"],"item4":"blah4","item5":"blah5"},{"item1":"Blah1","item2":"blah2","item3":["0100"],"item4":"blah4","item5":"blah5"},{"item1":"Blah1","item2":"blah2","item3":["0300"],"item4":"blah4","item5":"blah5"},{"item1":"Blah1","item2":"blah2","item3":["0200","0100"],"item4":"blah4","item5":"blah5"}];
var data2 = [{"CandidateName":"Mary","relatedId":["0100","0200"]},{"CandidateName":"John","relatedId":["0200"]},{"CandidateName":"Peter","relatedId":["0300","0100"]},{"CandidateName":"Paul","relatedId":["0300"]}];

var result = existingArray.map(function(o) {
  o.item6 = data2.filter(function(e) {
    return o.item3.some(function(a) {
      return e.relatedId.indexOf(a) != -1;
    })
  }).map(function(e) {
    return e.CandidateName;
  })
  return o;
})

console.log(result)

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

Learn how to utilize Jquery to create a dynamic slide effect that toggles the

I am looking to change a banner on click functionality. Currently, I have hidden the 2nd banner and banner 1 is displayed. When the arrow is clicked, I want banner 1 to hide and banner 2 to show. The challenge is that I attempted using HTML for this task. ...

Is there a definitive way to distinguish between scrollTop and scrollHeight in web development?

For instance, function checkingScroll(){ var newHeight = element.scrollHeight; var scrollTopValue = element.scrollTop; alert("The scrollHeight property is: " + newHeight + "px"); alert("The scrollTop property is: " + scrollTopValue ...

Locate the initial occurrence of a duplicated element within an array

I need to check for duplicate values in an array element. Within my array, I have multiple objects like {S:1,R:2,V:3}. My goal is to display an alert message if there are duplicate values for the "S" element in that array. My Approach: var arr=[{S:1,R:2 ...

Unable to get knockout sorting to function properly

I have been working on organizing my grid and here is the code that I have so far: ko.moveInGrid = { // Creating a view model class for grid population viewModel : function(config) { this.data = config.data; this.currentPageIndex = ...

React - Uncaught TypeError: Cannot access property 'renderSidebaritem' of an undefined object

Issue with React code - TypeError: Cannot read property 'renderSidebaritem' of undefined. (anonymous function) I have identified the problematic line and commented it out. It seems like there is an error related to the binding of 'this&apos ...

Utilizing Array Filters and State in React JS to Conceal Table Columns

I am currently working on converting this code into a functional component, but I am facing issues with the behavior of my arrays. EXPECTED OUTPUT: https://stackblitz.com/edit/antd-showhidecolumns Here is my modified version using functional components: ...

Ways to calculate the sum of multiple series in highcharts

By utilizing the Highcharts value-in-legend plugin available at http://www.highcharts.com/plugin-registry/single/10/Value-In-Legend, I have managed to partially implement a method for calculating a total value of multiple series. However, I am facing chall ...

JavaScript: What's the best way to update the URL in the address bar without triggering a page refresh?

Similar Question: How can I use JavaScript to update the browser URL without reloading the page? I've observed websites like GMail and GrooveShark altering the URL in the address bar without having to refresh the entire page. Based on my understa ...

Best practice for validating a form using React: Why the state doesn't update immediately with useState and onSubmit

I'm currently working on implementing a custom form validation for my React project using Typescript. However, I've encountered an issue with the useState hook not updating the state containing errors immediately upon form submission. Let me illu ...

How to access nested arrays within an array using PHP

I am looking to create an array similar to the one below: $data = array( array( "name" => "Name1", "id" => "ID1" ), array( "name" => "Name2", & ...

Activating HTML 5 mode within Angular

Currently working on my first Single Page Application in AngularJS, and I've run into a roadblock with the routing. I'm attempting to enable HTML 5 like so: .config(function ($routeProvider, $locationProvider) { $locationProvider.html5Mode( ...

Combining ctype structure and array in Python

I am currently working on developing a custom UDP protocol that includes both a header and data components. The header holds crucial information about the structure of the data. In order to define the header, a ctypes struct is used while the data is repr ...

Transforming jQuery into pure Javascript code

UPDATE SUCCESS! I've cracked the code. The solution was to include jQuery by adding it in Joomla through the template/index.php file with this line under "//Add Javascript Frameworks" JHtml::_('jquery.framework');. PROGRESS I'm seekin ...

Creating a four-dimensional array in PHP can be achieved by nesting multiple arrays within each

When I run a distinct query, I end up with a lot of data. Take a look at this picture of a busy cat: My goal is to group the final status by nodeid, portid, and total, which represents the total status. I need to create an array that looks like this: [ ...

Manifestation for JSON Firebug extension

In the process of developing a firebug extension, I encountered an issue with displaying JSON in the panel. Despite using a textarea to display the panel, the extension consistently crashes. Here is what I attempted: var template = domplate( { ...

Retrieve all rows, with a specific row positioned at the top of the heap

I have multiple domains stored in a table, all pointing to the same root directory on the server. As a result, each domain displays the exact same website. The list of domains from the table will be displayed on the website and I plan to loop through the f ...

Use the clientID property of the controlname element within JavaScript to access the element using the getElementById method with only

I have a customized compound control that I need to deactivate. This control includes a text field and a calendar component. I want to disable both the image and the text field. Here is how it is identified on the page. The control's name is "datepic ...

Discover additional and subtract options

I am trying to implement a "See more" and "See less" button functionality for my list items inside an unordered list using the code below, but it is not working as intended. $(document).ready(function() { var list = $(".partners__ul li"); var numTo ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Retrieve the selected options from the checkbox and transfer them to the input text field

In the following example, I am attempting to extract all values of the inputs once they are checked and display them in a text input that will be sent via email. However, I am facing an issue where only the last option is being printed in that input instea ...