"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this:

https://i.stack.imgur.com/HAPrJ.png

I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here's what I have so far:

skillMatrix[0]: {val: 2, agents: ['val1', 'val2', 'val3']

However, I've hit a snag and can't progress beyond this point.

    for (i = 0; i < q.length; i++) {
        skillMatrix[i] = {}
    }

$.ajax(getSkills).done(function (res) {

                var sg;

    $(res).find('td:nth-child(3)').each(function(){

                a = $(this).parent().find('td:nth-child(2)').text();
                a = a.split('.');

                if(a[1] == '') {
                first = a[3];
                last = a[2];
                }
                else {
                first = a[2];
                last = a[1];
                }
                reJoin = last + ' ' + first;

                var sg = $(this);
                sg = sg.text().split('_');
                sg = sg[3];

                for (i = 0; i < q.length; i++) {
                    if (q[i] == sg) {
                    skillMatrix[i].group = sg;
                    skillMatrix[i].ag = reJoin;
                    }
                }
    })

})

Answer №1

To start off, the first step is to gather the unique values from each row. This can be achieved by iterating through each row and adding the text of the second column to an array only if it's not already included. The following code snippet demonstrates how this can be implemented:

var arr=[];
    $("tr").each(function(){
      if(!arr.includes($(this).find('td:eq(1)').text())){
        arr.push($(this).find('td:eq(1)').text());
      }
    })

Next, iterate over each of these unique values and select the td element that contains the corresponding value from the arr array using:

$("tr td:nth-child(2):contains("+arr[i]+")")
.

Then, for each selected element, access its parent element and find the first column that includes the agent information:

$(this).parent().find("td:eq(0)").text()
.

Combine all these steps into a JavaScript object, resulting in the following example:

var arr=[];

$("tr").each(function(){
  if(!arr.includes($(this).find('td:eq(1)').text())){
    arr.push($(this).find('td:eq(1)').text());
  }
})
  var obj={};
for(var i=0;i<arr.length;i++)
{
var agents=[];
$("tr td:nth-child(2):contains("+arr[i]+")").each(function(){

agents.push($(this).parent().find("td:eq(0)").text());


});

obj[i]= {val: arr[i], agents:agents};
}

console.log(obj);
td{
border:solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>value 1</td>
      <td>2</td>
    </tr>
    <tr>
      <td>value 2</td>
      <td>3</td>
    </tr>
    <tr>
      <td>value 3</td>
      <td>2</td>
    </tr>
    <tr>
      <td>value 4</td>
      <td>1</td>
    </tr>
  </tbody>
</table>

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

Is it possible to categorize a JSON object based on its properties and then count the occurrences of each property within

I have an array of objects containing booking information and I need to calculate the count of each booking item in every object. const arr = [ { "ID" : 1, "Name":"ABC", "Bookings":[ { & ...

The array filtering functionality is not functioning as intended

Struggling with correctly filtering data in JavaScript. Here's an example where var1 = 20, var2 = 10, var3 = 30, var4 = 40. This is the code snippet: var variables = ['var1', 'var2', 'var3', 'var4'], values = [ ...

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

Error: Attempting to access index '0' of an undefined property in firebase and vuex

When using a vuex action to upload an image to Firebase and save the URL, everything seems fine until trying to retrieve the downloadUrl and adding it to the meetup database reference. The code I have looks like this: actions: { createMeetup ({commit ...

Encounter issues with v-for functionality when using Internet Explorer 11

I am facing an issue with the rendering of a table in a simple Vue instance. The document displays correctly on Firefox and Chrome, however, I encounter an error in IE11: [Vue warn]: Error when rendering root instance. I assumed that Vue is compatible ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...

Automatically scroll to the end of the data retrieved through ajax

I am currently developing a live chat website for my users and I am using ajax to fetch the chat messages. However, I am facing an issue where whenever I enter a new message, it does get added to the database and displayed, but the scroll doesn't auto ...

What could be causing my unique Angular custom date filter to output nonsensical results?

This is the Jade markup: .col-md-9 | {{client.person.date_of_birth | date:'standardDate'}} Here's the filter in Angular: .filter('standardDate', function($filter){ var dateFilter = $filter('date'); ...

Error TS2339 encountered in ngx-uploader: There is no property called 'lastModifiedDate' on the type 'File'

An issue has arisen in the code at node_modules/ngx-uploader/src/ngx-uploader/classes/ngx-uploader.class.ts(112,32): error TS2339: Property 'lastModifiedDate' is not found on type 'File'. Encountered this error while updating my An ...

Executing a script in the browser console automatically upon clicking a link can be achieved using Python

I am interested in executing JavaScript in my browser's DevTools console. Currently, I have managed to open a specific website through it. Is there a way to achieve this using Python? Here is the code I am currently using: url = 'http://some-we ...

Removing a parameter from a variable in jQuery and JavaScript

I have coded something and assigned it to a variable. I now want to replace that value with another one. Just so you know, I do most of my coding in perl. Specifically, I am looking to remove the menu_mode value. Any advice on this would be greatly appre ...

Check the status of the audio source URL using JavaScript

I am currently live streaming audio to my player using the Soundcloud API. <audio></aidio> <source src="soundcloud-track-url"></source> Within my code, I have added an onerror eventListener for both the <audio> and <sourc ...

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

What is the most efficient way to extract a key and its corresponding value from an object containing only one pair?

Currently, I am developing a recipeBox application using React JS. Within this application, there is a state defined as: this.state = { recipeArray: [] ...} Users have the ability to add recipes by pushing objects {recipe_Name : Ingredients} into tha ...

problem encountered when attempting to fetch a value through ajax

Here is an updated version of the code for my preview problem. The goal is to send and retrieve a value using ajax, but I'm encountering issues with sending the value and getting ajax to work properly. This revised code is easier to test on different ...

Issues arising from jQuery AJAX request in Chrome extension

BLUF: The AJAX call from my Chrome extension is not functioning properly. AJAX: $.ajax({ type: "GET", url: "http://weather.aero/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=KFBG&hour ...

Is there a way to modify a specific key value in all embedded objects using Mongoose?

I'm currently working on a chat application and I'm facing a challenge with implementing the 'seen' functionality. I need to update all chat messages in the database by setting the 'seen' column to true. Here is the schema st ...

JavaScript in Internet Explorer is showing an error message stating that it is unable to access the property '0' of an undefined or null

JavaScript Code function update() { var newAmt = 0; var newtable = document.getElementById("tbl"); for ( var i = 0; i < newtable.rows.length; i++) { innerTable = newtable.rows[i].cells[0].childNodes[0]; if ( (innerT ...

Identify and target a particular DIV based on the URL for customization

My webpage has a collection of frequently asked questions (FAQs) on a page called faq.html. Here is an example structure: <div id="faq1">...</div> <div id="faq2">...</div> I am looking to create a pulsating or highlighting effect ...

Processing information received through an ajax.post request

I want to establish a connection with a Node.js server on localhost using ajax to send data. For testing purposes, I attempted to send text input to the server and log it there. Here is my Post-Function that triggers upon button click: function sendDat ...