简体   繁体   中英

How can you map an array to a new array based on the key-value pairs in an object?

I'm writing a script that will score a test. The answers are verbal, each word of which corresponds to a particular number value from 1 to 5.

I created an object that documents those correspondences:

const answerValues = {
    "Consistently": 5,
    "Often": 4,
    "Sometimes": 3,
    "Rarely": 2,
    "Never": 1
  }

The answers are given in an array of arrays structured like this:

const answers = [
  ["Consistently, "Often", "Sometimes", "Rarely", "Never"],
  ["Often, "Sometimes", "Consistently", "Never", "Rarely"],
  ["Sometimes, "Rarely", "Consistently", "Rarely", "Often"]
]

What I need to do is to map the original answers to a new array that will instead be something like this:

const answerResults = [
  [5, 4, 3, 2, 1],
  [4, 3, 5, 1, 2],
  [3, 2, 5, 1, 4]
]

I can't seem to get this to work; any help would be much appreciated.

PS If need be, I can change the answers array into an object, if that will make this easier.

Use map

var output = answers.map( s => s.map( t => answerValues[t] ) )

Demo

 var answerValues = { "Consistently": 5, "Often": 4, "Sometimes": 3, "Rarely": 2, "Never": 1 }; var answers = [ ["Consistently", "Often", "Sometimes", "Rarely", "Never"], ["Often", "Sometimes", "Consistently", "Never", "Rarely"], ["Sometimes", "Rarely", "Consistently", "Rarely", "Often"] ]; var output = answers.map(s => s.map(t => answerValues[t])); console.log(output); 

Explanation

- use `map` to iterate `answers`,
-   use `map` for each `s` in `answers` and iterate the values
-     *replace* each value `t` with its `answerValues[t]`

You can map the outer array with the values of the object of the inner array.

 const answerValues = { Consistently: 5, Often: 4, Sometimes: 3, Rarely: 2, Never: 1 }, answers = [["Consistently", "Often", "Sometimes", "Rarely", "Never"],["Often", "Sometimes", "Consistently", "Never", "Rarely"], ["Sometimes", "Rarely", "Consistently", "Rarely", "Often"]], result = answers.map(a => a.map(k => answerValues[k])); console.log(result); 

Simple use nested map and then return the response using the answerValues map

 const answers = [ ["Consistently", "Often", "Sometimes", "Rarely", "Never"], ["Often", "Sometimes", "Consistently", "Never", "Rarely"], ["Sometimes", "Rarely", "Consistently", "Rarely", "Often"] ] const answerValues = { "Consistently": 5, "Often": 4, "Sometimes": 3, "Rarely": 2, "Never": 1 } const res = answers.map(answer => { return answer.map(resp => answerValues[resp]); }) console.log(res) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM