Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
How to group together same elements into a new Array

Below is an array containing some elements:

const arr = ['a', 'b', 'c', 'a', 'b', 'c', 'd']

So how can I create a new array where same elements are grouped together into a new array like this:

const arr = [['a','a'], ['b','b'], ['c','c'], ['d']]

Thank you for your time.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This can be achieved with the most generic of group by operations.

const arr = ['a', 'b', 'c', 'a', 'b', 'c', 'd'];

const grouped = Object.values(arr.reduce((a, n) => ((a[n] ??= []).push(n), a), {}));

console.log(grouped);

about 4 years ago · Juan Pablo Isaza Denunciar

0

The idea is to sort the array in ascending order, then iterate over it and take if the last char and the current char are the same and put them in an inner-array else create new inner-array of that char, do this process of accumulating till for loop iterate overall characters.

["a","a","b","b","c","c","d"]
//sort and do algorithm 
["a","a","b","b","c","c","d"]
//^---^   ^---^
[["a","a"],["b","b"],["c","c"],["d"]]

Implementation:

const arr = ["a", "b", "c", "a", "b", "c", "d"];
const chars = arr.sort((a, b) => a.localeCompare(b));
console.log(chars);
let res = [[]],
  lastChar = chars[0];
for (char of chars) {
  if (char == lastChar) {
    res[res.length - 1].push(char);
  } else {
    res.push([char]);
    lastChar = char;
  }
}

Result:

console.log(res); //[["a","a"],["b","b"],["c","c"],["d"]]
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is one way to do it. More explicit, but easier to understand and translate to other languages as well. Time: O(n), Space: O(n), n is number of elements in array

function process(arr) {
    const map = arr.reduce((acc, e) => {
        if (!acc.has(e)) {
            acc.set(e, 0);
        }
        acc.set(e, acc.get(e) + 1);
        return acc;
    }, new Map())

    const res = [];
    for (const[k, v] of map.entries()) {
        const localRes = [];
        for (let i = 1; i <= v; i++) {
            localRes.push(k);
        }
        res.push(localRes);
    }
    return res;
}

const arr = ['a', 'b', 'c', 'a', 'b', 'c', 'd']
console.log(process(arr));

Result:

[ [ 'a', 'a' ], [ 'b', 'b' ], [ 'c', 'c' ], [ 'd' ] ]
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda