How do I map a Set of Objects in typescript
Asked Answered
K

1

6

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

Knotts answered 22/2, 2022 at 19:35 Comment(3)
Set indeed does not have a map() method, and arrays have no max() method. You have to do something like this instead: Math.max(...Array.from(jobs).map((job) => job.priority))Silverware
Thats it! in the end I used .reduce((acc, curr)=> acc>curr?acc:curr, 0) but that's just because I need the default value to be 0Knotts
All right, wrote up an answer for completeness (but not touching the default of 0 because the whole max thing is out of scope for the question as asked).Silverware
S
9

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

Silverware answered 22/2, 2022 at 22:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.