I've been exploring more efficient ways to search through an array of objects as my current approach is too slow. The array I'm working with has the following structure:
[
{
fname: 'r7942y9p',
lname: 'gk0uxh',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f4f3fce1acfaf2d5f2f8f4fcf9bbf6faf8">[email protected]</a>',
phone: 2326571226
},
{
fname: 'hipnr9f6',
lname: 'rsnse5',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9d9699dbd89e86af88828e8683c18c8082">[email protected]</a>',
phone: 7863302156
},
...
I'm interested in searching the objects based on their email
and phone
properties and returning the first object that matches either the provided email or phone.
Question: Is there a more efficient alternative to
const log = data.find(item => {
return (item.email && item.email === email) || (item.phone && item.phone === phone)
});
I've created a simple benchmark to analyze this scenario:
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 = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ee9d8a85828688828a8588ae89838f8782c08d8183">[email protected]</a>', 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')
In the benchmark above, the data
array is populated with 50,000 random elements and searched for email or phone matches. My node server reports an execution time of approximately 2.5 ms. This means that if I were to search the data
array 10,000 times, which is a common scenario, I would have to wait for around 25 seconds. I'm looking for ways to optimize this process and make it faster.
It's important to note that the phone
or email
fields may not always be present in the data
array, hence the need for checks like
(item.email && item.email === email)