MichaelAngelo MichaelAngelo - 4 months ago 9
Javascript Question

Map array with arrays into a array

Lets say for example i have this array with arrays:

var arrayWithArrays = [["peter","director","40"],["marie","author","10"],["marie","author","6"],["peter","director","9"]];


I want a new array that will have this format (unique name,
all the hours for the unique name added up):

var chartData = [["peter", 49],["marie",16]];


I have tried allot of things but nothing works as expected.
Mapping doesnt work like expected

var temp = _.map(arrayWithArrays ,function(x){

if(chartData[x[0]]){
chartData[x[0]] += parseInt(x[2]);
}else{
chartData[x[0]] = parseInt(x[2]);
}
});


Old fashioned way also doesnt deliver

for (var x = 0; x < arrayWithArrays.length; x++) {
if(chartData.length != 0){
for (var i = 0; i < chartData.length; i++) {
if(chartData[i][0] == arrayWithArrays[x][0]){
chartData[i][2] += parseInt(arrayWithArrays[x][2]);
}else{
var array = [];
array[0] = arrayWithArrays[x][0];
array[1] = parseInt(arrayWithArrays[x][2]);
chartData.push(array);
}
}
}else{
var array = [];
array[0] = arrayWithArrays[x][0];
array[1] = parseInt(arrayWithArrays[x][2]);
chartData.push(array);
}
}


I think i am overthinking it and i make it more complex than it really is...someone has an idea to get me out of this headache ? I already spent 3 hours over this

Answer

You could use Array#forEach for it and use an object for the reference to the inserted array.

var arrayWithArrays = [["peter", "director", "40"], ["marie", "author", "10"], ["marie", "author", "6"], ["peter", "director", "9"]],
    result = [];

arrayWithArrays.forEach(function (a) {
    if (!this[a[0]]) {
        this[a[0]] = [a[0], 0];
        result.push(this[a[0]]);
    }
    this[a[0]][1] += +a[2];
}, Object.create(null));

console.log(result);

Extendet for role name and count

var arrayWithArrays = [["peter", "director", "40"], ["marie", "author", "10"], ["marie", "author", "6"], ["peter", "director", "9"]],
    result = [];

arrayWithArrays.forEach(function (a) {
    if (!this[a[0]]) {
        this[a[0]] = [a[0], 0, [a[1], 0]];
        result.push(this[a[0]]);
    }
    this[a[0]][1] += +a[2];
    this[a[0]][2][1]++;
}, Object.create(null));

console.log(result);