Neil Merton
Neil Merton

Reputation: 573

How to get distinct year from list of objects in Javascript

I've got the following object in Javascript and I'd like to return a list of distinct years from the createdOn value:

I've tried the following but it returns an empty array:

const things = [{
    "id": 1,
    "title": "First thing",
    "createdOn": "2017-12-07T15:44:50.123"
  },
  {
    "id": 2,
    "title": "Second thing",
    "createdOn": "2018-05-07T09:10:24.123"
  },
  {
    "id": 3,
    "title": "Third thing",
    "createdOn": "2018-12-07T12:07:50.123"
  },
  {
    "id": 4,
    "title": "Forth thing",
    "createdOn": "2018-12-07T16:39:29.123"
  }
]

console.log(things.map(thing => new Date(thing.createdOn).getFullYear()).filter((value, index, self) => self.indexOf(value) === index))

What am I missing here?

Many thanks in advance.

Upvotes: 5

Views: 1100

Answers (1)

Mohammad Usman
Mohammad Usman

Reputation: 39362

You are using a misspelled argument in callback to the .map() i.e replace thing with event. You may also use Set to get the unique values:

const data = [
  {"id": 1, "title": "First thing", "createdOn": "2017-12-07T15:44:50.123"}, 
  {"id": 2, "title": "Second thing", "createdOn": "2018-05-07T09:10:24.123"}, 
  {"id": 3, "title": "Third thing", "createdOn": "2018-12-07T12:07:50.123"}, 
  {"id": 4, "title": "Forth thing", "createdOn": "2018-12-07T16:39:29.123"}
];

const result = [...new Set(data.map(event => new Date(event.createdOn).getFullYear()))];

console.log(result);

Upvotes: 4

Related Questions