-2
I have the following array with a string inside.
let fruta = ['banana'];
fruit is the name of my array and banana is the string. my intention is to create a code that Mapeie the string 'banana' showing the position of each letter getting;
banana
b: 0
a: 1,3,5
n: 2,4
The first line is the entire string The second line is the position where the letter 'b' should be The third line are the positions where the letters 'a' should be The last line is the positions where the letters 'n' should be
I created the following command to perform the action I want;
//console.log(fruta);
let fruta = [
'banana'
];
function mapString(fruta, ) {
let map = {};
for (let i = 0; i < fruta.length; i++) {
let atual = fruta[i];
if (map[atual]) {
map[atual].push(i);
} else {
map[atual] = [i];
}
}
return map;
};
let stringMap = mapString(fruta);
for (let letter in stringMap) {
console.log(letter + ': ' + stringMap[letter]);
}
But when I spin the code the return is not;
banana
b: 0
a: 1,3,5
n: 2,4
The return is;
banana: 0
Because this is going wrong?
The function
mapString
should receive a single string, but you are passing the entire array. Then you could go through the fruit array, and for each of the fruits, call the function (something likefor (var f of fruta) { mapString(f) etc }
). Rename the array tofrutas
(plural) would help, as it becomes clearer that it is an array that can have more than one fruit (even if it only has one, it still has the plural name helps make the code clearer).– hkotsubo
I understood that I made the mistake when I passed the entire array, but I still don’t understand how I can pass a given string instead of the entire array
– PLUTAL GAMES
I already said in the comment above: if you want to use the array, do a
for
and call the function for each element. Or do not use array, use only string:var fruta = 'banana'; mapString(fruta)
– hkotsubo
Sometimes I forget the logic, forget that the computer does everything I tell it and I end up skipping steps. It worked perfectly as expected since it is the logic 'haha'. thank you endlessly, if there’s anything I can do to increase your status on the platform as a thank you, I will.
– PLUTAL GAMES
Please do not publish image code and don’t be rude, never negotiate reputation on the platform. Vote(up, down) and only agree to be voted (up, down) or accepted.
– Augusto Vasques