I have a feeling this question already exists, just can't find it. Is there a way to take a 2d array with x rows and 2 columns and merge multiple values into one row based on it having 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']]
So that it looks like this
[ [ 'Needs Work', 'Joe,Jill,Jack,Jack' ],
[ 'Complete', 'Sean,Joe' ],
[ 'Not Started', 'Laura' ] ]
CodePudding user response:
Considering the answer that you posted, I wrote the following function:
function create_union_array(initial_array) {
const temporal_object = {};
for (i in initial_array) {
const work_state = initial_array[i][0];
const people_name = initial_array[i][1];
if (temporal_object[work_state] == undefined) {
temporal_object[work_state] = [people_name]
} else {
temporal_object[work_state].push(people_name)
}
}
const output_array = [];
let iteration = 0;
for (i in temporal_object) {
output_array[iteration] = [i, temporal_object[i]]
iteration ;
}
return output_array;
}
Unlike yours, instead of returning the names in a concatenated string, this one returns the names in an array, in case you need to work with the names afterwards this would be a better option.
CodePudding user response:
Not sure if this the most efficient way.
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))]//gets set of distict 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])//filters array to only to current value
// console.log(filteredArray)
condensedArray.push([list[i], extractColumn(filteredArray, 1).toString()])
}
console.log(condensedArray)
}