what you mean about sum two arrays, you want merge (concatenate), because in javascript + operator you can only use to add numbers or concatenate strings.I'm trying to find the sum of two arrays.
const array1 = [
{ Name:'James', Subject:'English', 202309:10, 202310:30, 202311:50 },
{ Name:'Neoh', Subject:'Math' , 202309:20, 202310:15, 202311:90 }
];
const array2 = [
{ Name:'James', Subject:'English', 202309:10, 202310:30, 202311:50 },
{ Name:'Neoh', Subject:'Math' , 202309:20, 202310:15, 202311:90 }
];
const combinedArray1 = array1.concat(array2); //
console.log(combinedArray1);
const combinedArray2 = [...array1, ...array2]; // using the spread operator
console.log(combinedArray2);
const array1 = [
{ Name:'James', Subject:'English', 202309:10, 202310:30, 202311:50 },
{ Name:'Neoh', Subject:'Math' , 202309:20, 202310:15, 202311:90 }
];
const array2 = [
{ Name:'James', Subject:'English', 202309:10, 202310:30, 202311:50 },
{ Name:'Neoh', Subject:'Math' , 202309:20, 202310:15, 202311:90 }
];
const arraySum = array1.map((item1, index) => {
const item2 = array2[index];
return {
Name: item1.Name,
Subject: item1.Subject,
202309: item1[202309] + item2[202309],
202310: item1[202310] + item2[202310],
202311: item1[202311] + item2[202311],
};
});
console.log(arraySum);
to add the 202309:10 itself you need to do this element by element,
// Define two arrays with data
const array1 = [
{ Name: 'James', Subject: 'English', 202309: 10, 202310: 30, 202311: 50 },
{ Name: 'Neoh', Subject: 'Math', 202309: 20, 202310: 15, 202311: 90 },
{ Name: 'Mateo', Subject: 'Chinese', 202310: 20, 202311: 5 }
];
const array2 = [
{ Name: 'James', Subject: 'English', 202309: 10, 202310: 30, 202311: 50 },
{ Name: 'Neoh', Subject: 'Math', 202309: 20, 202310: 15, 202311: 90 },
{ Name: 'Mateo', Subject: 'Chinese', 202309: 80, 202311: 10 }
];
// Combine the two arrays into one
const combinedArray2 = [...array1, ...array2];
//console.log(combinedArray2);
// Initialize an empty array to store the summed data
const summedArray = combinedArray2.reduce((accumulator, current) => {
// Check if an existing item with the same Name and Subject exists in the accumulator
const existingItem = accumulator.find(item => item.Name === current.Name && item.Subject === current.Subject);
if (existingItem) {
// If an existing item is found, add the values of fields starting with '2023...'
for (const key in current) {
if (!existingItem[key]) existingItem[key] = 0;
if (key.startsWith('2023')) existingItem[key] += current[key];
}
} else {
// If no existing item is found, add a new entry to the result array
accumulator.push(current);
}
return accumulator;
}, []);
console.log(summedArray);
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.