JavaScript count duplicates in an Array of objects | Example code

Use Object.values() and reduce() methods to return new array of objects to count duplicates in array of objects. Another way in JavaScript is use Map and spread syntax …

JavaScript count duplicates in an Array of objects Example

HTML example code

Using Reduce method

<!DOCTYPE HTML> 
<html> 
<body> 
	
	<script>
		const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]

		const result = Object.values(array.reduce((r, e) => {
			let k = `${e.x}|${e.y}`;
			if(!r[k]) r[k] = {...e, count: 1}
				else r[k].count += 1;
			return r;
		}, {}))

		console.log(result)
	</script> 
</body> 
</html>	

Output:

JavaScript count duplicates in an Array of objects

Using Map and spread syntax …

const array = [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 1, y: 2 }, { x: 3, y: 12 } ]

const result = [...array.reduce((r, e) => {
  let k = `${e.x}|${e.y}`;
  if(!r.has(k)) r.set(k, {...e, count: 1})
  else r.get(k).count++
  return r;
}, new Map).values()]

console.log(result)

Do comment if you have any doubts and suggestions on this JS Array Object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.