function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
// idades de 1 a 50
const idades = [];
for (var age = 1; age <= 50; age++) {
idades.push(age);
}
const users = [];
// insere mil usuários com cada idade
for (var i = 0; i < 1000; i++) {
for (const age of idades) {
users.push({ age: age, name: "Fulano " + i });
}
}
shuffle(users); // embaralha, só pra não ficar todas as idades em ordem
// buscar por essas idades
const ages = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
for (const age of ages) {
const result = [];
for (var i = 0; i < users.length; i++) {
if (users[i].age === age) {
result.push(users[i]);
}
}
}
// a criação do índice faz parte do algoritmo, mas é feita apenas uma vez
const usersByAge = {};
users.forEach((user) => {
if (!usersByAge[user.age]) {
usersByAge[user.age] = [];
}
usersByAge[user.age].push(user);
});
// procura por todas as idades desejadas
for (const age of ages) {
const result = usersByAge[age];
}