0

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 !!

1 Answer 1

2

Use the bracket notation to access the property :

if (prev.indexOf(curr[criteria]) === -1) {prev.push(curr[criteria])}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.