1

I've got an array of sessions defined something like this:

const sessions = [{id: 1, eventYear: "2019"},{id: 2, eventYear: "2018"},{id: 3, eventYear: "2018"}];

and I want to create a new array of objects with just the eventYear "2018"

I tried mapping over the array and if session.eventYear === eventYear return the session record, otherwise return nothing, but got a list of objects 3 long (not 2) with one undefined record. I wanted just 2 records returned.

I have the following working, but it feels uncomfortably non functional and long. I'd appreciate a suggestion for how to make this more concise in modern JavaScript

const sessionsForEventYear = [];
sessions.map(function(session) {
  if (session.eventYear === eventYear) {
    sessionsForEventYear.push(session);
  }
});
Pete
  • 3,111
  • 6
  • 20
  • 43
  • 1
    If you're not interested in the return value of `.map()` you shouldn't be using it. In this case you should use `.forEach()` or `.reduce()` – Andreas Aug 23 '20 at 16:49

1 Answers1

2

Use Array.prototype.filter instead:

const sessions = [{id: 1, eventYear: "2019"},{id: 2, eventYear: "2018"},{id: 3, eventYear: "2018"}];
const sessionsForEventYear = sessions.filter(({ eventYear }) => eventYear === '2018');
console.log(sessionsForEventYear);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Does filter create a new object or does it carry references to the old one? – Pete Aug 23 '20 at 16:49
  • The *array* is new, but the items of the prior array are not copied - the new array holds references to the same objects. – CertainPerformance Aug 23 '20 at 16:50
  • Is map the same as filter in that regard. Thanks! I did not realize that subtlety. – Pete Aug 23 '20 at 18:04
  • Also, I looked at the other question this was closed in favor of, and I did not see any discussion around what is returned (that is, referrence or new objects). Seems to me that makes it a non-dupe. – Pete Aug 23 '20 at 18:05