Combining rows using a specific column in Javascript

Could this particular question already be in existence, but just hasn't been found yet? Is there a method for consolidating multiple values into one row of a 2D array with x rows and 2 columns based on them sharing the same element in the first column?

[['Needs Work', 'Joe'], ['Needs Work', 'Jill'], ['Needs Work', 'Jack'], ['Complete', 'Sean'], ['Complete', 'Joe'], ['Not Started', 'Laura'], ['Needs Work', 'Jack']]

The desired output should resemble:

[ [ 'Needs Work', 'Joe,Jill,Jack,Jack' ],
  [ 'Complete', 'Sean,Joe' ],
  [ 'Not Started', 'Laura' ] ]

Answer №1

It's puzzling if this is the most optimum approach.

function myFunction() {
  var array = [['Needs Work', 'Joe'], ['Needs Work', 'Jill'], ['Needs Work', 'Jack'], ['Complete', 'Sean'], ['Complete', 'Joe'], ['Not Started', 'Laura'], ['Needs Work', 'Jack']];
  const extractColumn = (arr, n) => arr.map(row => row[n])
  var list = [...new Set(extractColumn(array, 0))]//acquires unique values from first column
  // console.log(list)
  var condensedArray = []
  for (var i = 0; i < list.length; i++) {
    var filteredArray = array.filter(row => row[0] == list[i])//narrows down array to current value
    // console.log(filteredArray)
    condensedArray.push([list[i], extractColumn(filteredArray, 1).toString()])

  }
  console.log(condensedArray)
}

Answer №2

Based on the answer you provided, I came up with the following function:

function generateUnionArray(initialArray) {
  const temporaryObject = {};
  for (let i in initialArray) {
    const workState = initialArray[i][0];
    const peopleName = initialArray[i][1];
    if (temporaryObject[workState] === undefined) {
      temporaryObject[workState] = [peopleName];
    } else {
      temporaryObject[workState].push(peopleName);
    }
  }
  const outputArray = [];
  let iteration = 0;
  for (let i in temporaryObject) {
    outputArray[iteration] = [i, temporaryObject[i]];
    iteration++;
  }
  return outputArray;
}

Unlike your approach, my function returns the names in an array rather than a concatenated string. This can be more useful if you need to manipulate the names individually later on.

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 there a way to keep the modal window open in React without it automatically closing?

I have been working on a modal window implementation in React. I defined a state variable called modalbool to control the visibility of the modal window. The modal window is displayed only when modalbool is set to true. Additionally, I created a parent com ...

Struggling to retrieve the JSON information, but encountering no success

Here is the javascript code snippet: $.getJSON("validate_login.php", {username:$("#username").val(), password:$("#password").val()}, function(data){ alert("result: " + data.result); }); And here is the corresponding php code: <?ph ...

Doing server side function calls from the client in NodeJs

I recently embarked on a journey to learn web development and am eager to make server-side data changes when invoking client functions. Take a look at my sample server setup: const fs = require('fs'); const path = require('path'); con ...

Iterating over an array of objects and executing asynchronous operations

I am currently working with NextJS and managing an array of assets (images) within my state. The task at hand is to post these images to the API. To accomplish this, I have a specific object that handles the posting process using the following syntax: let ...

Seeking out and upgrading essential information: how to do it effectively?

I am working with a document in a mongo collection that looks like this: { "_id" :"sdsfsfd323323323ssd", "data" : { "('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [ "$B_Add-Server", ...

Tips on deactivating a button after it has been clicked once within a 24-hour period and reactivating it the following day with the use of JavaScript and Angular

Is it possible to disable my button after one click per day, and then automatically re-enable it the next day once a user has entered details using the submit button? I need assistance with JavaScript or AngularJS for this functionality. ...

Tips for recognizing a specific object ID within an array in order to modify the status of an element within that object

My goal is to accurately identify a specific panel within an expanded array and link that panel's ID to a button, while also ensuring the button is disabled when no panels are expanded or more than one panel is expanded. However, I am encountering iss ...

Concealing the print option while utilizing PDFObject in conjunction with PDF.js

When displaying a file using pdf.js, I encountered issues with the print button and other functionalities. I was able to hide the buttons using CSS for Chrome, but not for Internet Explorer, where I had to resort to using JavaScript. While the JavaScript ...

Modifying two distinct charts according to the choices made in two independent dropdown menus

In my current project, I am facing a challenge with integrating two separate dropdowns containing UFC fighter names. The goal is to display a plot showing the KD (Knockdown) data for the selected fighters over time when their names are chosen from both dro ...

Is there a way to access the Flask global in AngularJS?

I'm in the process of developing an internal web application using Flask that connects to various clusters. The majority of the URLs begin with /cluster/cluster_name, which is why I've implemented the following code in my blueprints: cluster = B ...

A simple way to retrieve the computed value from one ng-model and assign it to a different ng

I am facing an issue where I have 3 ng-models and I need to fetch calculated data from the first two into the third one using angularjs I attempted a solution but it doesn't seem to work as expected Below is the HTML code snippet: var urlt = ' ...

"What is the best approach for setting up an Azure Web App to host both an Express static site and API

Setting up an Express app was a breeze for me, but when it comes to deploying it on Azure Web App, I'm hitting some roadblocks! The structure of my app is quite simple: a static web app with its own API. Requests to /website.com/api are forwarded to ...

Why is the React Util js file not functioning properly when using an absolute path?

Help needed! I'm utilizing create-react-app without ejecting. I can't seem to figure out why this code snippet is not functioning correctly. import { capitalizeFirst } from 'util/util.js'; //This line is causing issues import AdminIn ...

Error message "auth/code-expired" is triggered when Firebase Multi Factor Authentication for a web application detects that the verification code has expired

While working on adding multi-factor authentication to my Angular web application, I encountered an error message stating: "auth/code-expired", "The SMS code has expired. Please resend the verification code to try again.", even though I ...

Change the behavior of an onclick event on the second click

I'm trying to make a button on my website that not only plays music when clicked but also changes the text inside the button to "Go to SoundCloud" and redirects to SoundCloud. Currently, I have been able to achieve both functions separately - redirect ...

How can I differentiate between an unreachable server and a user navigating away in a $.ajax callback function?

Situation: You have a situation where several $.ajax requests to the server are still in progress. All of them end with xhr.status === 0 and xhr.readyState === 0. Possible reasons for this issue: The server might be down (EDIT: meaning it is unreachabl ...

Delightful Bootstrap Tabs with Dynamic Content via Ajax

My website has a lot of tabs designed with Bootstrap. I wanted to make them responsive, so I tried using a plugin called Bootstrap Tabcollapse from https://github.com/flatlogic/bootstrap-tabcollapse (you can see a demo here: http://tabcollapse.okendoken.co ...

Using ReactJS to search for and replace strings within an array

A feature of my tool enables users to input a string into a textfield and then checks if any words in the input match with a predetermined array. If the user's string contains a specific name from the array, I aim to replace it with a hyperlink. I&a ...

Version 10 of Internet Explorer seems to be overlooking the XMLHttpRequest setting of 'xhr.withCredentials = true'

Encountering an issue with a cross-domain ajax call in IE10 (in IE10 mode, not compatibility). Situation: Two domains involved, http://a and http://b. Cookie set for http://b. Currently on page http://a. Goal is to make a CORS request to http://b using X ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...