As I delve into the world of searching and sorting algorithms, I've encountered a challenge with implementing a binary search on an array of customer objects. This particular array is sorted by both first and last name.
The objective here is to locate a customer's email address within the data set and retrieve its corresponding index.
A snippet of the data structure is shown below:
[
{
"username": "Maude.Torp",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94c0f5edf5badff1e6f8e1fff1a1a7d4f3f9f5fdf8baf7fbf9">[email protected]</a>",
"address": {
"street": "Rowe Fields",
"suite": "Suite 231",
"city": "Tiannamouth",
"zipcode": "07584-6653",
"geo": { "lat": "75.0283", "lng": "-17.1824" }
},
"phone": "795-827-5446 x18366",
"website": "nico.com",
"company": {
"name": "Champlin, Feest and Barrows",
"catchPhrase": "Object-based user-facing orchestration",
"bs": "transition integrated content"
},
"firstName": "Maida",
"lastName": "Feeney"
},
...
]
The current implementation of my binary search function is as follows:
function searchByEmail(email, customers) {
let start = 0;
let end = customers.length - 1;
while (start <= end) {
let middle = Math.floor((start + end) / 2);
if (customers[middle] === email) {
return middle;
} else if (customers[middle] < email) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return -1;
}
While this function works for sorted arrays of numbers by returning the index of the desired key, it only outputs -1 when applied to arrays of objects like the one described above. Any tips on adjusting this algorithm to accommodate object searches?