Skip to content
Advertisement

Find duplicates of an array and replace it with its number

Say I have an array:

arr = [25, 25, 25, 20, 15, 10, 10, 5];

and I want to count up the number of duplicates (ie. three 25s and 2 10s) and make a new array that becomes:

newArr = ['25 * 3', 20, 15, '10 * 2', 5];

How should I go about doing this? Thanks!

Advertisement

Answer

You can use a Array#forEach loop to iterate through each item of the array, keeping track of how many times each item has been seen before.

Demo:

JavaScript

The same technique but smaller using Array#reduce:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement