Find a string within a jQuery array that has multiple elements per object

Viewed 111

I've got an array of employee's and assigned to each employee are a few elements.

Sample of array below:

var employees = [
                   {"name":"Johhny Test","salary":"1","email":"abc@123.com"},
                   {"name":"Mike Milbury","salary":"10","email":"184895@hdsjhfs.com"}
                ];

I've got a means of gathering the employee's last name and I'm storing it in a variable. I'd like to be able to search for the indexOf the last name housed in this variable so that I know at which position within the array that match is made.

So for instance, this array could be 100 items in size. Ideally I want to know that someone with the last name of "johnson" is in position 50 of this array. That way, I can go in and get the salary and email associated with their record from position 50 in the array.

The code I've got so far is this:

var lname = "Test";
var lnameMatch = employees.indexOf(lname);
console.log(lnameMatch);

This isn't working though - my console is logging -1, suggesting that it doesn't exist in the array. Is there a way that I can specify a element of that array to search against?

Almost like employees(name).indexOf(lname) where it is searching against the name element?

Or am I going about this all wrong and there is perhaps an easier less messy way to accomplish this?

1 Answers

You can use .findIndex:

const employees = [
  {"name":"Johhny Test","salary":"1","email":"abc@123.com"},
  {"name":"Mike Milbury","salary":"10","email":"184895@hdsjhfs.com"}
];
const lastName = "Test";

const index = employees.findIndex(employee => {
  const { name = '' } = employee;
  const nameParts = name.split(' ');
  const lname = nameParts[nameParts.length-1];
  return lastName === lname;
});

console.log(index);
console.log(employees[index]);

Related