Reputation: 771
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.
Upvotes: 1
Views: 643
Reputation: 386578
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);
Upvotes: 2
Reputation: 68393
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]`
Upvotes: 3
Reputation: 281686
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)
Upvotes: 1