Suma de valores de propiedad de objeto de matriz en una nueva matriz de objetos en Javascript
arrays javascript-objects (5)
Aqui tienes:
function convert(inputArray) {
var temp = {};
for(var i = 0; i < inputArray.length; i++) {
var subject = inputArray[i].subject;
// check if there is already an entry with this subject in the temp array
if(temp.hasOwnProperty(subject)) {
// if it is already in the list, add the marks and the noOfStudents
temp[subject].marks = temp[subject].marks + parseInt(inputArray[i].marks, 10);
temp[subject].noOfStudents = temp[subject].noOfStudents + parseInt(inputArray[i].noOfStudents, 10);
}
else {
// if it is not yet in the list, add a new object
temp[subject] = {
subject: subject,
marks: parseInt(inputArray[i].marks, 10),
noOfStudents: parseInt(inputArray[i].noOfStudents, 10)
}
}
}
// the temporary array is based on the subject, you are however interested on the effective value object
var result = [];
for(var entryKey in temp) {
result.push(temp[entryKey]);
}
return result;
}
Tengo una matriz de objetos donde necesito la suma de valores de propiedad de objeto en una nueva matriz de objetos,
Entrada:
var inputArray = [
{ subject: ''Maths'', marks: ''40'', noOfStudents: ''5'' },
{ subject: ''Science'', marks: ''50'', noOfStudents: ''16'' },
{ subject: ''History'', marks: ''35'', noOfStudents: ''23'' },
{ subject: ''Science'', marks: ''65'', noOfStudents: ''2'' },
{ subject: ''Maths'', marks: ''30'', noOfStudents: ''12'' },
{ subject: ''History'', marks: ''55'', noOfStudents: ''20'' },
.
.
.
];
Salida que necesito,
var outputArray = [
{ subject: ''Maths'', marks: ''70'', noOfStudents: ''17'' },
{ subject: ''Science'', marks: ''115'', noOfStudents: ''18'' },
{ subject: ''History'', marks: ''95'', noOfStudents: ''43'' },
.
.
.
];
Quiero suma de calificaciones y no de estudiantes de asignaturas en una nueva matriz de objetos. Habría N número de otros objetos sujetos (es decir, Geografía, Física, etc.) en la matriz de entrada.
La solución que utiliza las
Array.forEach
,
parseInt
y
Object.keys
:
var summed = {}, result;
inputArray.forEach(function (obj) {
obj[''marks''] = parseInt(obj[''marks'']);
obj[''noOfStudents''] = parseInt(obj[''noOfStudents'']);
var subj = obj[''subject''];
if (!summed[subj]) {
summed[subj] = obj;
} else {
summed[subj][''marks''] += obj[''marks''];
summed[subj][''noOfStudents''] += obj[''noOfStudents''];
}
}, summed);
result = Object.keys(summed).map((k) => summed[k]);
console.log(JSON.stringify(result, 0, 4));
La salida:
[
{
"subject": "Maths",
"marks": 70,
"noOfStudents": 17
},
{
"subject": "Science",
"marks": 115,
"noOfStudents": 18
},
{
"subject": "History",
"marks": 90,
"noOfStudents": 43
}
]
Puede hacerlo con el parámetro opcional
forEach
y
thisArg
var inputArray = [
{ subject: ''Maths'', marks: ''40'', noOfStudents: ''5'' },
{ subject: ''Science'', marks: ''50'', noOfStudents: ''16'' },
{ subject: ''History'', marks: ''35'', noOfStudents: ''23'' },
{ subject: ''Science'', marks: ''65'', noOfStudents: ''2'' },
{ subject: ''Maths'', marks: ''30'', noOfStudents: ''12'' },
{ subject: ''History'', marks: ''55'', noOfStudents: ''20'' },
], outputArray = [];
inputArray.forEach(function(e) {
if(!this[e.subject]) {
this[e.subject] = { subject: e.subject, marks: 0, noOfStudents: 0 }
outputArray.push(this[e.subject]);
}
this[e.subject].marks += Number(e.marks);
this[e.subject].noOfStudents += Number(e.noOfStudents);
}, {});
console.log(outputArray)
Puede usar forEach para iterar y generar la nueva matriz
var inputArray = [
{ subject: ''Maths'', marks: ''40'', noOfStudents: ''5'' },
{ subject: ''Science'', marks: ''50'', noOfStudents: ''16'' },
{ subject: ''History'', marks: ''35'', noOfStudents: ''23'' },
{ subject: ''Science'', marks: ''65'', noOfStudents: ''2'' },
{ subject: ''Maths'', marks: ''30'', noOfStudents: ''12'' },
{ subject: ''History'', marks: ''55'', noOfStudents: ''20'' }
],
res = [],
key = {};
inputArray.forEach(function(v) {
if (key.hasOwnProperty(v.subject)) { // check subject already added by using key object
res[key[v.subject]].marks += Number(v.marks); //incase already exist parse number and add
res[key[v.subject]].noOfStudents += Number(v.noOfStudents);
} else {
key[v.subject] = res.length; // create index entry in key object
res.push({ // push the value
''subject'': v.subject,
''marks'': Number(v.marks),
''noOfStudents'': Number(v.noOfStudents)
})
// if you pushed the original object then the original array also will get updated while adding the mark, so never push the refernce
}
})
console.log(res);
Usando el método forEach
var inputArray = [
{ subject: ''Maths'', marks: ''40'', noOfStudents: ''5'' },
{ subject: ''Science'', marks: ''50'', noOfStudents: ''16'' },
{ subject: ''History'', marks: ''35'', noOfStudents: ''23'' },
{ subject: ''Science'', marks: ''65'', noOfStudents: ''2'' },
{ subject: ''Maths'', marks: ''30'', noOfStudents: ''12'' },
{ subject: ''History'', marks: ''55'', noOfStudents: ''20'' }
],
key = {};
res=inputArray.reduce(function(arr,v) {
if (key.hasOwnProperty(v.subject)) { // check subject already added by using key object
arr[key[v.subject]].marks += Number(v.marks); //incase already exist parse number and add
arr[key[v.subject]].noOfStudents += Number(v.noOfStudents);
} else {
key[v.subject] = arr.length; // create index entry in key object
arr.push({ // push the value
''subject'': v.subject,
''marks'': Number(v.marks),
''noOfStudents'': Number(v.noOfStudents)
})
// if you pushed the original object then the original array also will get updated while adding the mark, so never push the refernce
}
return arr;
},[])
console.log(res);
FYI:
puede evitar el objeto
key
utilizando el método
find()
, pero el rendimiento puede ser un poco más lento.
Solo otra propuesta con un objeto como tabla hash.
var inputArray = [{ subject: ''Maths'', marks: ''40'', noOfStudents: ''5'' }, { subject: ''Science'', marks: ''50'', noOfStudents: ''16'' }, { subject: ''History'', marks: ''35'', noOfStudents: ''23'' }, { subject: ''Science'', marks: ''65'', noOfStudents: ''2'' }, { subject: ''Maths'', marks: ''30'', noOfStudents: ''12'' }, { subject: ''History'', marks: ''55'', noOfStudents: ''20'' }],
outputArray = [];
inputArray.forEach(function (a) {
if (!this[a.subject]) {
this[a.subject] = { subject: ''Maths'', marks: ''0'', noOfStudents: ''0'' };
outputArray.push(this[a.subject]);
}
this[a.subject].marks = (+this[a.subject].marks + +a.marks).toString();
this[a.subject].noOfStudents = (+this[a.subject].noOfStudents + +a.noOfStudents).toString();
}, Object.create(null));
console.log(outputArray);