Created
June 2, 2020 13:59
-
-
Save joalbertg/c67682f9397cb005328ccf1dfc931782 to your computer and use it in GitHub Desktop.
javascript: array to hash for search
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
// 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