Skip to content

Instantly share code, notes, and snippets.

@joalbertg
Created June 2, 2020 13:59
Show Gist options
  • Save joalbertg/c67682f9397cb005328ccf1dfc931782 to your computer and use it in GitHub Desktop.
Save joalbertg/c67682f9397cb005328ccf1dfc931782 to your computer and use it in GitHub Desktop.
javascript: array to hash for search
// array to hash for search
const users = [];
const products = [];
const elem = 10;
const keyBy = (arr, key) => arr.reduce((acc, el) => {
//console.log('acc', acc);
//console.log('acc[el]', el);
//console.log('acc[el[key]]', el[key]);
acc[el[key]] = el;
return acc;
}, {});
for (let i = 0; i < elem; i++) {
users.push({
id: i,
nombre: `nombre-${i}`
});
}
for (let i = 0; i < elem; i++) {
products.push({
id: i,
nombre: `nombre-producto-${i}`,
user_id: Math.floor(Math.random() * elem)
});
}
const keyedUsers = keyBy(users, 'id');
console.time();
const mezclados = products.map(x => ({
...x,
//user: users.find(y => y.id === x.user_id)
user: keyedUsers[x.user_id]
}));
console.timeEnd();
console.log('mezclados:', mezclados[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment