Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
How to transfer MAP.values into Arrays efficiently?

In the example below, you see some noisy but straightforward implementation.

Initial Situation

We have an initial Array with repeating information.

const listArray = [
  { songBy: 'George Michael',  uid: 'A',  whatEver: 12},
  { songBy: 'George Michael',  uid: 'A',  whatEver: 13},
  { songBy: 'George Michael',  uid: 'A',  whatEver: 14},
  { songBy: 'Michael Jackson', uid: 'B',  whatEver: 12},
  { songBy: 'Michael Jackson', uid: 'B',  whatEver: 16},
]

STEP 1

We create a new Map because we distinctly want to save artist names, which means → no artist-name-repetitions (and we also want to get rid of the third column, by the way).

We need to use songBy as key, for some reason. We change it within the value into name.

const listMap = new Map();

listArray.forEach(
  row => listMap.set(
   row.songBy, {name: row.songBy, uid: row.uid}
  )
);

STEP 2

Finally, we need an array with its values:

const distinctListArray: Array<any> = [];

listMap.forEach(value => distinctListArray.push(value));

So we achieve a result as an Array of distinct objects in the form of:

[
  name: string
  uid: string
]

Question:

To my mind, this implementation is too noisy and not so elegant. There are too many steps and too many variables. (This example here is a simplified version of a real code I cannot share).

Is there a way to simplify that code and make it more efficient?

EDIT: See online: TypeScript Playground

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Convert the list to [key, value] pairs using Array.map(), and then create the map from the list. Convert the Map back to an array by applying Array.from() to the Map.values() iterator (TS playground):

const listArray = [{"songBy":"George Michael","uid":"A","whatEver":12},{"songBy":"George Michael","uid":"A","whatEver":13},{"songBy":"George Michael","uid":"A","whatEver":14},{"songBy":"Michael Jackson","uid":"B","whatEver":12},{"songBy":"Michael Jackson","uid":"B","whatEver":16}]

const distinctListArray = Array.from(
  new Map(listArray.map(({ songBy, uid }) => 
    [songBy, { name: songBy, uid }]
  )).values()
)

console.log(distinctListArray)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!