Reputation: 325
I am trying to write a decode function where the arguments are a string of letters (in this case the alphabet) and an array of numbers. I want to use the .map method on the array to return the coded message as a string. The numbers are positive integers.
The function, given the array passed in, should return the string "beans".
I cannot figure out the logic. Here is what I have:
function decoder(key, code) {
var arr = key.split('');
var result = "";
arr.map(function(item) {
for(var i = 0; i <= code.length; i++) {
if(item[i] === code[i]) {
result += item;
}
}
return result;
});
}
console.log(decoder("abcdefghijklmnopqrstuvwxyz", [1, 4, 0, 13, 18 ]));
Upvotes: 0
Views: 733
Reputation:
Others have already given a more solid solution, but you can use your initial idea of utilizing a for loop.
function decoder(key, code) {
var arr = key.split('');
var result = "";
for (var i = 0; i < code.length; i++) {
result += arr[code[i]];
}
return result;
}
console.log(decoder("abcdefghijklmnopqrstuvwxyz", [1, 4, 0, 13, 18 ]));
Upvotes: 1
Reputation: 51881
You can map code
array to get character at each position and then join it:
function decoder(key, code) {
return code.map(function(c) {
return key.charAt(c);
}).join('');
}
console.log(decoder("abcdefghijklmnopqrstuvwxyz", [1, 4, 0, 13, 18 ]));
Upvotes: 1
Reputation: 4724
A perfect match for Array.prototype.reduce():
function decoder(arr, indices){
return indices.reduce(function(previousValue, currentValue){
return previousValue + arr[currentValue];
}, "");
}
alert(decoder("abcdefghijklmnopqrstuvwxyz", [1, 4, 0, 13, 18 ]));
Upvotes: 3