-1

Can someone help me with filtering an array of objects in javascript? I have an array of users such as:

var users = [

  {
    first: 'Jon',
    last: 'Snow',
    email: 'jon@got.com'
  },

  {
    first: 'Ned',
    last: 'Stark',
    email: 'ned@got.com'
  },

  {
    first: 'tywin',
    last: 'Lannister',
    email: 'tywin@got.com'
  },

]

And I'm trying to write a function to search through the array of objects:

function search(str, users) {

  var results = users.filter(function(el) {
    return (el.first === str || el.last === str || el.email === str);
  });

  return results;

}

However, doing it this way, my search parameter str would have to exactly match the first/last/email value of the user array.. I need the function be able to search based on a substring... Can someone help?

Thanks in advance!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200

1 Answers1

4

Use String#indexOf method

function search(str, users) {

  var results = users.filter(function(el) {
    return (el.first.indexOf(str)>-1 || el.last.indexOf(str)>-1 || el.email.indexOf(str));
  });

  return results;
}

UPDATE 1 : To make it case insensitive use String#toLowerCase method (Only supports in latest browsers).

function search(str, users) {

  var lStr = str.toLowerCase();
  var results = users.filter(function(el) {
    return (el.first.toLowerCase().indexOf(lStr)>-1 || el.last.toLowerCase().indexOf(lStr)>-1 || el.email.toLowerCase().indexOf(lStr));
  });

  return results;
}

UPDATE 2 : More simplified version using Array#some method.

function search(str, users) {
  return  users.filter(function(el) {
    return Object.keys(el).some(function(k){
      return el[k].toLowerCase().indexOf(str.toLowerCase())
    });
  });
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188