TheRealPapa TheRealPapa - 2 months ago 13
jQuery Question

Filter array of objects to get distinct values into new array

I have created a fiddle here of my question, with the help of some of the answers below.

I have an array of objects. An individual object in the a array contains:

obj1, obj2, obj3...


An example of one of the object is:

{
client_id: "85"
id: 1477
organisation_id: 5
task_project_id: 26
project_name: "Reiciendis adipisci fugiat."
project_description: "Soluta consequatur labore et dolores"
task_description: "Qui sunt at aut."
task_end_time: null
task_start_time: "2016-05-21 09:00:00"
transaction_id: null
}


I want to generate a new array of objects from this first array containing distinct entries of task_project_id. The new array should contain distinct objects structured per below:

{
task_project_id: 26
project_name: "Reiciendis adipisci fugiat."
}


I have tried
jQuery.grep
,
array.filter
,
array.map
but to no avail. I also cannot seem to find examples using "extract array of distinct objects" as search. Could someone point me to an example please. Thanks.

Answer

array.map should work just fine:

var b = a.map(function(e) {
  return {
    task_project_id: e.task_project_id,
    project_description: e.project_description
  }
});

// make entries unique
b = b.filter(function(v, i) { return b.indexOf(v) == i; });
Comments