Skip to content

Instantly share code, notes, and snippets.

@EdixonAlberto
Created April 26, 2021 19:09
Show Gist options
  • Save EdixonAlberto/fe24014054dd9496a30bcb73b512a595 to your computer and use it in GitHub Desktop.
Save EdixonAlberto/fe24014054dd9496a30bcb73b512a595 to your computer and use it in GitHub Desktop.
Algorithm for grouping or collecting equal elements in an array
const nroList = [1, 4, 1, 3, 2, 4];
const collector = [];
let qty = 1;
nroList.forEach((nro, index) => {
qty = 1;
if (!collector.find(item => item.nro === nro)) {
for (let i = 0; i < nroList.length; i++) {
const nroCurrent = nroList[i];
if (i === index) continue;
else if (nroCurrent === nro) qty++;
}
collector.push({ nro, qty });
}
});
console.log(collector);
/* out:
0: {nro: 1, qty: 2}
1: {nro: 4, qty: 2}
2: {nro: 3, qty: 1}
3: {nro: 2, qty: 1}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment