2

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":"[email protected]"},
                   {"name":"Mike Milbury","salary":"10","email":"[email protected]"}
                ];

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?

2
  • I'm a little confused. The example doesn't use jQuery. Instead are you looking for employees.filter? Commented Dec 20, 2020 at 11:13
  • Apologies for the confusion, downstream my function is going to use jQuery to render an element based on being able to properly source the correct info from the array, Will check out filter and see if that's what I need! Commented Dec 20, 2020 at 11:15

1 Answer 1

2

You can use .findIndex:

const employees = [
  {"name":"Johhny Test","salary":"1","email":"[email protected]"},
  {"name":"Mike Milbury","salary":"10","email":"[email protected]"}
];
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]);

Sign up to request clarification or add additional context in comments.

2 Comments

what if there are multiple surnames, you should get either the last or everything after the first one
@majedbadawri - this worked awesome, you're the MVP! Really appreciate this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.