2

I was given a task to create a object based array of users. Then create a a function which takes in a parameter and returns another array matching the values compared within the first arr

var users = [
  {
    firstname : "jetlag",
    lastname: "son"
  },
  {
    firstname : "becky",
    lastname: "love"
  },
  { 
    firstname : "just",
    lastname: "me"
  }
];

function matchName(name) {
  for (var i = 0; i < users.length; i++) {
      if(users[i].firstname == name) {
          return users[i];
      } else {
          console.log('user does not exist')
      }
  }
}

console.log(matchName("jetlag"));

I am able to match a specfic username, but what if I just enter jinto the matchName("j"), i would like to return two objects.

Any help on this would be great. http://jsfiddle.net/dv9aq0m7/

Thanks.

Shivam
  • 2,208
  • 3
  • 24
  • 39

5 Answers5

2

You can use Array.prototype.filter and return an array of objects that match your criteria. Something like this:

var users = [...];
function matchName(name) {
    return users.filter(function (user) {
        return user.firstname.indexOf(name) !== -1;
    });
}
Oleg
  • 9,341
  • 2
  • 43
  • 58
2

Your current code returns the first complete match. This code:

  if(users[i].firstname == name) {
      return users[i];
  }

checks that the two strings are equal and then the return statement will only return that matched value. The function also stops once it has returned any value.

So you need to make two small changes. First you need to keep track of all users that fit the criteria, and you should use different logic to check that the string starts with another string.

Revised code might look like this:

function matchName(name) {
  var validUsers = [];                        //the array of users that pass the logic
  for (var i = 0; i < users.length; i++) {  
      if(users[i].firstname.lastIndexOf(name) === 0) { //this is "starts with" logic
           validUsers.push(users[i]);         //add the element if it's valid
      } 
  }
  //I moved the logic for no matching users the outside the loop
  if (validUsers.length === 0) 
      console.log('No matching users found')
  return validUsers;
}

Note: Based on the text you were printing, I moved the logic for printing that no users were found outside the loop by checking the number of elements in the validUsers array. This will print once only if there are no matching users.

Here's a fork to your fiddle

Community
  • 1
  • 1
ryanyuyu
  • 6,366
  • 10
  • 48
  • 53
  • Looks great, I would just ass `break;` after showing the user does not exist error, so it does not print that statement three times. Thanks! – Shivam Apr 30 '15 at 19:36
  • @Shivam updated based on the text of that console log. – ryanyuyu Apr 30 '15 at 19:42
1

So you want to compare the prefix, not equality.

You can use

users[i].firstname.indexOf(name) === 0

to test if a user.firstname starts with name.

And use filtering to retrieve matches:

function matchName (name) {
    return users.filter(function (user) {
        return user.firstname.indexOf(name) === 0;
    });
}

This always returns an array, which I think is a better interface.

Kijewski
  • 25,517
  • 12
  • 101
  • 143
0

Use Array.prototype.filter() for this. Your approach will only return the first match as an object.

function matchName(name) {
    return users.filter(function (item) {
        return item.firstname == name
    }   
}

Then use length of result to test if matches exist

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

You could use regular expressions in order to match any part of your name, not just the beggining.

function matchName(name) {
  var pattern = new RegEx(name, "i");
  for (var i = 0; i < users.length; i++) {
      if(users[i].firstname.search(pattern)) {
          return users[i];
      } else {
          console.log('user does not exist')
      }
  }
}
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60