This is my current array
0:{modelNumber: "123456789", balance: { amount:1000, currency:"EUR" }}
1:{modelNumber: "987654321", balance: { amount:2000, currency:"EUR" }}
2:{modelNumber: "322353466", balance: { amount:1500, currency:"GBP" }}
3:{modelNumber: "892347522", balance: { amount:1000, currency:"USD" }}
4:{modelNumber: "931883113", balance: { amount:3000, currency:"INR" }}
5:{modelNumber: "854300564", balance: { amount:2500, currency:"GBP" }}
6:{modelNumber: "931883113", balance: { amount:3000, currency:"INR" }}
7:{modelNumber: "854300564", balance: { amount:3500, currency:"USD" }}
I'm trying to return a new array, with each currency and the total value for each currency.
Like below return the total amount for each currency in the array above
0:{currency: "EUR", totalAmount: 3500}
1:{currency: "GBP", totalAmount: 5000}
2:{currency: "USD", totalAmount: 4500}
3:{currency: "INR", totalAmount: 6000}
My approach initially:
//the current array
let theInitialArray = state.vehicle;
const results = theInitialArray.reduce((accumalator, current) => {
const { currency } = current.balance;
if (accumalator[currency]) {
accumalator[currency].push(current);
return accumalator;
}
accumalator[currency] = [current];
return accumalator;
}, {});
let frank = Object.keys(results)
let jim = [];
let expectedOutput = theInitialArray.filter((x) => {
for (let i=0; i < frank.length; i++) {
if (x.balance.currency === frank[i]) {
jim.push({'currency': frank[i], 'amount': x.balance.amount});
}
}
});
console.log('expectedOutput', expectedOutput)
return expectedOutput