Reputation: 1292
I have this array of objects and want the unique elements given a specific key. The array looks like this:
var items = [
{name: "item1", year : 2013, value : 100},
{name: "item1", year : 2012, value : 97},
{name: "item3", year : 2013, value : 93 },
{name: "item3", year : 2012, value : 91 },
{name: "item2", year : 2012, value : -6 },
{name: "item2", year : 2011, value : -5 },
{name: "item4", year : 2012, value : -36 },
{name: "item3", year : 2011, value : 93 },
{name: "item4", year : 2013, value : -35 },
{name: "item1", year : 2011, value : 98},
{name: "item2", year : 2013, value : -7 },
{name: "item4", year : 2011, value : -37 },
{name: "item5", year : 2013, value : 58 },
{name: "item5", year : 2012, value : 55 },
{name: "item5", year : 2011, value : 54 }];
I get the list of unique elements for the key name with the following function:
var unique = function (arr) {
return arr.reduce(function (prev, curr) {
if (prev.indexOf(curr.name) === -1) {prev.push(curr.name)}
return prev;
}, [])}
so when I do console.log(unique(items)) I get the correct array:
[ 'item1', 'item3', 'item2', 'item4', 'item5' ]
If I change name
with year
in curr.name i get the correct result.
I want to do a higher order function so I can both pass the array I am working on and the key, so I would do unique(items, 'name')
or alternatively unique(items, 'year')
however when I transform my unique function to this:
var unique = function (arr, criteria) {
return arr.reduce(function (prev, curr) {
if (prev.indexOf(curr.criteria) === -1) {prev.push(curr.criteria)}
return prev;
}, [])}
and I do console.log(unique(items, 'name'))
I get undefined
!?
and if I do console.log(unique(items, name)
I get an error ReferenceError: name is not defined !!
Upvotes: 0
Views: 191
Reputation: 382130
Use the bracket notation to access the property :
if (prev.indexOf(curr[criteria]) === -1) {prev.push(curr[criteria])}
Upvotes: 2