Home > OS >  How to transfer MAP.values into Arrays efficiently?
How to transfer MAP.values into Arrays efficiently?

Time:02-27

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 want to get rid of 3rd column and distinctly save artist names. (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

CodePudding user response:

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)

  • Related