## Calculate average of duplicates in a javascript array of objects

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);
}
}
});```

You could take a combined key for the wanted properties and replace the `price` format to a numerical parsable format.

```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" }],
keys = ['market', 'commodity', 'month', 'year'],
count = {},
result = data.reduce(function (r, o) {
var key = keys.map(function (k) { return o[k]; }).join('|');
if (!count[key]) {
count[key] = { sum: +o.price.replace(',', '.'), data: JSON.parse(JSON.stringify(o)) };
count[key].data.count = 1;
r.push(count[key].data);
} else {
count[key].sum += +o.price.replace(',', '.');
count[key].data.price = (count[key].sum / ++count[key].data.count).toString();
}
return r;
}, []);

console.log(result);```
`.as-console-wrapper { max-height: 100% !important; top: 0; }`

Calculate average of array of objects per key value using reduce , Here is possibly an even more functional programming style solution, which makes use of a temporary ES6 Map object. This has the advantage� How to check whether an Array of Objects contain duplicates by key Consider an Array of student Objects with each object having a key id. We have to perform a validation whether multiple objects with the same Id is present in the Array or not.

Group prices together for each item by adding them to an array in your `reduce` call. You can keep track of which items are duplicated in the same function. Then use loop over the duplicate items to compute the averages.

Note I had to change your price `74,99` to `74.99` to parse more easily. You'll probably want some sort of localization/globalization library if this is critical in your use case.

```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"}
];

function parsePrice(str) {
// TODO: localization
return +str;
}

function formatPrice(num) {
return num.toFixed(2);
}

function getHashKey(item) {
return JSON.stringify([item.market, item.commodity, item.month, item.year]);
}

var duplicatedItems = {};
var prices = data.reduce(function(result, current) {
var key = getHashKey(current);
if (key in result) {
result[key].push(parsePrice(current.price));
duplicatedItems[key] = current;
} else {
result[key] = [parsePrice(current.price)];
}
return result;
}, {});
var avg = Object.keys(duplicatedItems).map(function(key) {
var item = duplicatedItems[key];
var avgPrice = prices[key].reduce(function(acc, price) { return acc + price; }, 0) / prices[key].length;
return {
market: item.market,
commodity: item.commodity,
price: formatPrice(avgPrice),
month: item.month,
year: item.year
};
});

console.log(avg);```

Count duplicates in a JavaScript array, A further improvement can be gained if you delete duplicates from the use over 10000 calls to random arrays 1000 items long with a max range of min); max = Math.max(mem, max); } console.log("Mean memory use O(n� Use JavaScript to calculate if duplicate values exist in a single array. Various methods will give you different time complexities and efficiencies. View a written version of this tutorial on my

You could insert the values into a new array and merge if it already exists:

``` const result = [];

outer: for(const {  market, commodity,  price, month, year } of input) {
for(const other of result) {
if(market === other.market && commodity === other.commodity && month === other.month && year === other.year) {
other.prices.push(+price);

continue outer;
}
}
result.push({ market, commodity, prices: [+price], month, year });
}

for(const group of result)
group.price = group.prices.reduce((a, b) => a + b, 0) / group.prices.length;
```

How to get all unique values (remove duplicates) in a JavaScript , Asymptotic Analysis � Worst, Average and Best Cases � Asymptotic Notations � Little o Given an array which contains some values, the task is to remove the duplicate elements from the array. If the current value does not exist in the output array with unique values, then Count variable is used to add the. For finding duplicate values in JavaScript array, you’ll make use of the traditional for loops and Array reduce method. Using For Loop Let’s see how you can find duplicates in an array using for loop. The logic is you’ll separate the array into two array, duplicate array and unique array.

Average of an array? - JavaScript, function average (numbers) { let sum = 0; for (let i = 0; Array.find()? I'm not sure. The JavaScript Array class is a global object that is used in the Arrow Function JavaScript Remove Duplicates in Excel dllhost.exe COM� JavaScript automatically converts an array to a comma separated string when a primitive value is expected. This is always the case when you try to output an array. These two examples will produce the same result:

Collections - Laravel, avg(). The avg method returns the average value of a given key: \$average However, you pass a callback to the countBy method to count all items by a custom value: The duplicates method retrieves and returns duplicate values from the collection: If the collection contains arrays or objects, you can pass the key of the� The purpose of this article is to share with you the best ways to remove duplicate objects from JavaScript Array based on specific property/key. We will also analyze their performance in terms of execution time for different lengths of the array.

Chapter 7: Arrays, For example, to declare a variable, numbers that can hold an array of integers, we would nextInt( ); } // Calculate and print the average int sum = 0; for (int i = 0; � How to count duplicate value in an array in javascript. 1136. November 30, 2017, at 10:16 AM. Currently, I got an array like that: Duplicates in an array

• You can make your MCVE runnable using Stack Snippets (the `[<>]` toolbar button; here's how to do one).
• Why is `price` a string?
• @Giox, now with `count` in the result set.
• There is a trick that @NinaScholz is using there. After pushing the data to the result array (in the `r.push(count...` line), she relies on the fact that javascript is a "pass by reference" language. You need to understand that when she updates the price in `count` object (last line of the else block) she is also updating the result array. I think it would benefit you to start from scratch and try to solve the problem without using `reduce` first.