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:

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

let result = [], seenBefore = [];

arr.forEach((item) => {
  let seen = seenBefore.indexOf(item);
  if (seen !== -1) return result[seen].count++;
  result.push({ name: item, count: 1 });
  seenBefore.push(item);
});

result = result.map(({ name, count }) =>
  count > 1 ? `${name} * ${count}` : name
);

console.log(result);

The same technique but smaller using Array#reduce:

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

let result = arr
  .reduce(
    (acc, item) => {
      acc[1].indexOf(item) !== -1 ? acc[0][acc[1].indexOf(item)].count++ : (acc[0].push({ name: item, count: 1 }), acc[1].push(item));
      return acc;
    },
    [[], []]
  )[0]
  .map(({ name, count }) => (count > 1 ? `${name} * ${count}` : name));

console.log(result);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement