У меня есть массив объектов:
[
{"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"}
]
Я пытаюсь собрать дубликаты по средней цене .
Таким образом, ключами к идентификации дублированных строк являются все свойства, кроме цена , которые должны быть агрегированы по среднему значению.
В данных выше, например, строки 5 и 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"
являются дубликатами, и я хочу объединить их и получить среднее значение их цены.
Я пытался использовать функцию уменьшение , но не могу понять, как определить дублирующиеся значения, особенно если они не отсортированы.
Я публикую код, но он бесполезен, так как я не могу понять, как идентифицировать дубликаты с помощью 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);
}
}
});
Вот jsfiddle, где я пытался понять, как работает функция Reduce:
https://jsfiddle.net/brainsengineering/7tmdx0kg/7/