I have an array of objects:
[
{"market": "Qacha's nek","commodity": 55,"price": "90","month": "04","year": "2017"},
{"market": "Mohales Hoek","commodity": 55,"price": "75","month": "04","year": "2017"},
{"market": "Mafeteng","commodity": 55,"price": "75","month": "04","year": "2017"},
{"market": "Maseru","commodity": 55,"price": "69","month": "04","year": "2017"},
{"market": "Butha-Buthe","commodity": 55,"price": "66","month": "04","year": "2017"},
{"market": "Leribe","commodity": 55,"price": "64","month": "04","year": "2017"},
{"market": "Butha-Buthe","commodity": 55,"price": "65","month": "04","year": "2017"},
{"market": "Thaba-Tseka","commodity": 55,"price": "82","month": "04","year": "2017"},
{"market": "Thaba-Tseka","commodity": 55,"price": "81","month": "04","year": "2017"},
{"market": "Maseru", "commodity": 55,"price": "74,99","month": "04","year": "2017"}
]
I'm trying to aggregate duplicates by price average.
So the keys to identifying duplicated rows are all the properties except price, that must be aggregated by average.
In the data above, for example, line 5 and 7:
5) "market": "Butha-Buthe","commodity": 55,"price": "66","month": "04","year": "2017"
7) "market": "Butha-Buthe","commodity": 55,"price": "65","month": "04","year": "2017"
are duplicates and I want to merge them and make the average of their price value.
I was trying to use the reduce function, but I can't figure out how to identify duplicated values, especially if they are not sorted.
I post the code, but it's useless as I can't understand how to identify duplicates with reduce:
var data = [
{"market": "Qacha's nek","commodity": 55,"price": "90","month": "04","year": "2017"},
{"market": "Mohales Hoek","commodity": 55,"price": "75","month": "04","year": "2017"},
{"market": "Mafeteng","commodity": 55,"price": "75","month": "04","year": "2017"},
{"market": "Maseru","commodity": 55,"price": "69","month": "04","year": "2017"},
{"market": "Butha-Buthe","commodity": 55,"price": "66","month": "04","year": "2017"},
{"market": "Leribe","commodity": 55,"price": "64","month": "04","year": "2017"},
{"market": "Butha-Buthe","commodity": 55,"price": "65","month": "04","year": "2017"},
{"market": "Thaba-Tseka","commodity": 55,"price": "82","month": "04","year": "2017"},
{"market": "Thaba-Tseka","commodity": 55,"price": "81","month": "04","year": "2017"},
{"market": "Maseru","commodity": 55,"price": "74,99","month": "04","year": "2017"}
];
var avg = data.reduce(function(result, current) {
console.log(result,current);
if(!result){
result=current;
}
else {
if(result.market==current.market){
console.log(current.market);
}
}
});
Here a jsfiddle where I was trying to understand how the reduce function works: https://jsfiddle.net/brainsengineering/7tmdx0kg/7/
[<>]toolbar button; here's how to do one).pricea string?