How do I map a Set of Objects in typescript

Viewed 752

First time trying typescript.

I have an object that looks like

interface Job {
//... some data
    priority: number
}

and I want to return the highest priority from a Set of Jobs (note: not the Job itself, but the actual value). So naturally I just tried:

// let jobs: Set<Job> = fetchJobs();
jobs.map((job) => job.priority).max()
// or
jobs.values().map((job) => job.priority).max()

But it tells meUncaught TypeError: jobs.map is not a function

1 Answers

Set objects do not have a map() method, so it's not surprising that you're getting errors. You might be thinking of the map() method on Array objects instead. A Set is not an Array, although both are iterable. Luckily you can convert any iterable into an Array in several ways:

You can pass it to the static Array.from() method:

const jobArray = Array.from(jobs); // Job[]

Or you can spread it into an array literal:

const jobArray = [...jobs]; // Job[]

Note that the values() method of a Set produces the very same iterator that is used when you treat the Set as an iterator, so while you could use it, it's unnecessary:

const jobArray = Array.from(jobs.values()); // same thing

const jobArray = [...jobs.values()]; // also same thing

Once you have transformed the Set into an Array you can use map() and then process the result as needed:

const max = Math.max(...jobArray.map(j => j.priority)); // number

Playground link to code

Related