I am trying to find a better way to search an array of objects as my current method is much too slow. I have an array that looks like this:
[
{
fname: 'r7942y9p',
lname: 'gk0uxh',
email: 'afit9og@gmail.com',
phone: 2326571226
},
{
fname: 'hipnr9f6',
lname: 'rsnse5',
email: 'ryv47qi@gmail.com',
phone: 7863302156
},
...
I want to search its objects by email
and phone
and return the first object that has a given phone OR email.
Question: Is there a faster way than
const log = data.find(item => {
return (item.email && item.email === email) || (item.phone && item.phone === phone)
});
I have put together this simple benchmark:
const data = [];
let r = len => Math.random().toString(36).substring(len);
let n = (min, max) => Math.round(Math.random() * (max - min));
for(let i = 0; i < 50000; i++){
data.push(
{
fname: r(5),
lname: r(7),
email: `${r(6)}@gmail.com`,
phone: n(10000000000, 20000000000)
}
)
}
const email = 'sdklhfldkf@gmail.com', phone = 19027931232;
console.time('search_time');
const log = data.find(item => {
return (item.email && item.email === email) || (item.phone && item.phone === phone)
});
console.timeEnd('search_time')
console.log(log ? 'Found':'Not Found')
question from:
https://stackoverflow.com/questions/65621754/how-to-faster-search-an-array-of-objects 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…