Created
April 26, 2021 19:09
-
-
Save EdixonAlberto/fe24014054dd9496a30bcb73b512a595 to your computer and use it in GitHub Desktop.
Algorithm for grouping or collecting equal elements in an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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