2016-03-01 6 views
5

ho una matrice con un numero di oggetti con i tasti corrispondenti:Aggiungere valori delle chiavi corrispondenti in array di oggetti

[{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}] 

voglio scorrere l'array e se le chiavi corrispondono voglio aggiungere i risultati di ciascuno e restituire un oggetto con la somma di ciascuna chiave.

cioè

{a: 6, b: 9, c: 6, d: 3} 

Il codice ho attualmente è

function combine() { 
    var answer = []; 
    for(var i in arguments){ 
    answer.push(arguments[i]) 
    } 

answer.reduce(function(o) { 
    for (var p in o) 
     answer[p] = (p in answer ? answer[p] : 0) + o[p]; 
     return answer; 
    }, {}); 
} 

riesco a trovare la risposta here se dovessi utilizzare la libreria di sottolineatura, però vorrei farlo senza l'utilizzo di una libreria . Penso di avere difficoltà a capire come funziona il metodo reduce - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Qualsiasi aiuto su come risolvere questo problema sarebbe molto apprezzato. Inoltre, penso che sia una risposta che dovrebbe essere da qualche parte su SO senza dover usare una libreria.

Grazie in anticipo.

+0

citano anche l'uscita si stanno ottenendo rn. –

risposta

1

Passa attraverso ogni oggetto e aggiungilo.

var a = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}]; 
 
    var ans = {}; 
 

 
    for(var i = 0; i < a.length; ++i){ 
 
     for(var obj in a[i]){ 
 
     ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj]; 
 
     } 
 
    } 
 
document.write(JSON.stringify(ans));


ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj]; 

This line is the same as  
// check if the object already exists(or not falsy) in answer, if Yes add that value to the new value 
if(ans[obj]) 
{ 
    ans[obj] = ans[obj] + a[i][obj]; 
} 
// else create a new object in the answer and set it to the value from the array 
else 
{ 
    ans[obj] = a[i][obj]; 
} 
+0

grazie, ha funzionato. Tuttavia, sono un po 'confuso da questa riga 'ans [obj] = ans [obj]? ans [obj] + a [i] [obj]: a [i] [obj]; '. Ti dispiacerebbe spiegare nella tua risposta? –

1

provare questo

resobj = {}; 
 
[{a: 2,b: 5,c: 6}, {a: 3,b: 4,d: 1}, {a: 1,d: 2}].forEach(function(v) { 
 

 
    var keys = Object.keys(v); 
 
    for (i = 0; i < keys.length; i++) { 
 
    if (typeof resobj[keys[i]] == 'undefined') { 
 
     resobj[keys[i]] = Number(v[keys[i]]); 
 
    } else { 
 
     resobj[keys[i]] += v[keys[i]]; 
 
    } 
 
    } 
 

 
}) 
 

 
document.write(JSON.stringify(resobj))

1

Yo ur funzione di callback reduce() richiede due argomenti:

  1. Il risultato restituito per il valore precedente (o il valore iniziale se il primo)
  2. Il valore corrente nel circuito

Si dovrebbe anche passare un oggetto vuoto come secondo parametro da ridurre. . Questa è quella che si compila

var input = [ 
 
    {a: 2, b: 5, c: 6}, 
 
    {a: 3, b: 4, d: 1}, 
 
    {a: 1, d: 2} 
 
]; 
 

 
var answer = input.reduce(function(prev, curr) { 
 
    for (var p in curr) { 
 
     prev[p] = (prev[p] || 0) + curr[p]; 
 
    } 
 

 
    return prev; // this will be passed as prev in the next iteration or returned as the result. 
 
}, {}); // The {} is the initial value passed as prev 
 

 
console.log(answer);

0

Ancora un'altra soluzione a ridurre:

var result = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}].reduce(function(prev, current) { 
 
    Object.keys(current).forEach(function(key) { 
 
     prev[key] = (prev[key] || 0) + current[key]; 
 
    }); 
 
    return prev; 
 
}, {}); 
 

 
document.write('<pre>' + JSON.stringify(result, 0, 2) + '</pre>');

0

Basta usare Array#forEach() e un oggetto per il risultato .

var data = [{ a: 2, b: 5, c: 6 }, { a: 3, b: 4, d: 1 }, { a: 1, d: 2 }], 
 
    obj = {}; 
 

 
data.forEach(function (o) { 
 
    Object.keys(o).forEach(function (k) { 
 
     obj[k] = (obj[k] || 0) + o[k]; 
 
    }); 
 
}) 
 
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

2

Utilizzando Array.reduce() e Array.map()

var tab = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}]; 

function sum(tab) { 
    return tab.reduce((a, b) => { 
    Object.keys(b).map(c => a[c] = (a[c] || 0) + b[c]); 
    return a; 
    }); 
} 

console.log(sum(tab));