Reputation: 25
I've searched through similar questions and tried to solve the issue on my own, but my programming skills are weak.
I have an array like:
[{"city": "Amsterdam", "year": "2013", "amount": "450"},
{"city": "Rotterdam", "year": "2013", "amount": "620"},
{"city": "Geneva", "year": "2014", "amount": "530"},
{"city": "Rotterdam", "year": "2015", "amount": "350"}]
and I want to transform it using "city" and "year" to get "amounts". E.g. Rotterdam:[620,N/A,350]. "N/A" because value for year 2014 is missing. I was checking map function etc. but my skills are to weak. In the end I want to create a tabular view with years (horizontal) and cities (vertical). Please advice. Thanks
Upvotes: 0
Views: 57
Reputation: 5133
I don't think this is programming skills but algorithm skills. Here is a code doing what you want:
var amounts = [{"city": "Amsterdam", "year": "2013", "amount": "450"},{"city": "Rotterdam", "year": "2013", "amount": "620"},{"city": "Geneva", "year": "2014", "amount": "530"},{"city": "Rotterdam", "year": "2015", "amount": "350"}],
formattedAmounts = {}
;
for (var i = 0; i < amounts.length; i++) {
var amount = amounts[i];
if (undefined === formattedAmounts[amount.city]) {
formattedAmounts[amount.city] = {};
}
formattedAmounts[amount.city][amount.year] = amount.amount;
}
console.log(JSON.stringify(formattedAmounts));
alert(JSON.stringify(formattedAmounts));
function getCityAmount(city) {
var years = [2013, 2014, 2015],
cityAmounts = []
;
for (var i = 0; i < years.length; i++) {
cityAmounts.push(
formattedAmounts[city] && formattedAmounts[city][years[i]]
? formattedAmounts[city][years[i]]
: 'N/A'
);
}
return cityAmounts;
}
console.log(JSON.stringify(getCityAmount('Amsterdam')));
alert(JSON.stringify(getCityAmount('Amsterdam')));
function getCitiesAmounts() {
var citiesAmounts = [];
for (var i = 0; i < amounts.length; i++) {
citiesAmounts.push(getCityAmount(amounts[i].city));
}
return citiesAmounts;
}
console.log(JSON.stringify(getCitiesAmounts()));
alert(JSON.stringify(getCitiesAmounts()));
Upvotes: 1