Nermin
Nermin

Reputation: 935

Array of values from object where order is determined by another array

I have an array:

const markets= [
    "SWE",
    "FIN",
    "NZL",
]

and an object:

const entries = {
  "FIN": 1,
  "NZL": 100,
  "SWE": 10,
}

I want an array with the expected output to be:

const values = [
  10,
  1,
  100
]

So the order of the resulting array is determined by the first, "markets" array, taking the help of the object keys being the same as the markets values.

They can not be sorted by magnitude, alphabetically, or in any other such way.

Edit: The array and object can be assumed to contain the same set of entries, it's just the order of these entries that do not necessarily match.

Upvotes: 1

Views: 56

Answers (2)

AlexAV-dev
AlexAV-dev

Reputation: 1175

const markets= [
    "SWE",
    "FIN",
    "NZL",
]

const entries = {
  "FIN": 1,
  "NZL": 100,
  "SWE": 10,
}

const values = markets.map(rec => entries[rec])

console.log(values)

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Can do

let values = markets.map(m => entries[m]);

Upvotes: 2

Related Questions