-1

Lets suppose we have an array of objects like this:

var people = [
    {first: "John", last: "Doe"}, 
    {first: "Alan", last: "Doe"}, 
    {first: "John", last: "Black"}
];

How can we filter this array in jQuery if only one condition is selected by the user, for instance he want´s only the Doe last names (using a select form with two fields: first name, last name), hence the first name is not selected.

Thanks in advance.

BillCode
  • 3
  • 4
  • http://api.jquery.com/filter/ – Amit Kumar Ghosh Jan 02 '17 at 07:57
  • https://jsfiddle.net/aghosh08/bL8bxk02/ – Amit Kumar Ghosh Jan 02 '17 at 08:02
  • There is one problem. As suggested in the question there is a form selection with two fields - first name, last name. The selection is parsed as an array of two elements. If just one filed is selected (for instance the last name), the other field is passed as null. What would the filtering look like with one field null or not? – BillCode Jan 02 '17 at 10:30

2 Answers2

2

As suggested use .filter() to filter the array:

var people = [
    {first: "John", last: "Doe"}, 
    {first: "Alan", last: "Doe"}, 
    {first: "John", last: "Black"}
];

var filteredPeople = people.filter(function(person){
   return person.last === 'Doe'
});

console.log(JSON.stringify(filteredPeople, 4, 0));
Jai
  • 74,255
  • 12
  • 74
  • 103
  • There is one problem. As suggested in the question there is a form selection with two fields - first name, last name. The selection is parsed as an array of two elements. If just one filed is selected (for instance the last name), the other field is passed as null. What would the filtering look like with one field null or not? – BillCode Jan 02 '17 at 10:32
0

already answered in https://stackoverflow.com/a/19590901/2409250

var result = people.map(function(a) {return a.first;});

this is what you would do

Community
  • 1
  • 1
masadwin
  • 422
  • 2
  • 5
  • 11