3aluw
January 17, 2021, 11:03am
1
I had a challenge that says :
you have an array of these items :
const items = ["gold cup", "puppy", "sword", "whale's tooth", "squid tentacle", "other"];
and this array shows items’ price respectively :
> const prices = [5, 4, 10, 20, 100, 1];
create a function that calculate the value "the price " of some chosen items which are located in ChosenItem array.
So I used nested for loop for that. But eventually it didn’t work.
in the example i had chosen a specific ChosenItem array.
function PricesCalculator() {
let ChosenIems = ["puppy", "sword"];
let price = 0;
for (i = 0; i < ChosenIems.length; i++) {
for (x = 0; x < items.length; x++) {
if (ChosenIems[i] === items[x]) {
price += prices[x];
}
}
}
return price;
}
ofk8vb
January 17, 2021, 4:00pm
2
Before taking a deep look at your code, I see that in your nested for loop you wrote
for(x = 0; x < items.length; i++){
....
}
did you mean to increment x after each nested for loop but accidentally put i++?
3aluw
January 18, 2021, 8:31am
3
Ah, it was a typing mistake, i had already corrected it.
thanks for the note.
the console says price is not defined.
ILM
January 18, 2021, 12:28pm
4
what’s the whole code you have in the editor?
3aluw
January 19, 2021, 9:25am
5
it all there
const items = ["gold cup", "puppy", "sword", "whale tooth", "squid tentacle"];
const prices = [5, 4, 10, 20, 100, 1];
let TotalPrice = 0;
let ChosenIems = ["puppy", "sword","eagle eye"];
function PricesCalculator() {
for (i = 0; i < ChosenIems.length; i++) {
for (x = 0; x < items.length; x++) {
if (ChosenIems[i] === items[x]) {
TotalPrice += prices[x];
}
else if (ChosenIems[i] !== items[x]) {
TotalPrice += 1;
}
}
}
return TotalPrice;
}
console.log(PricesCalculator(), );
ILM
January 19, 2021, 10:02am
6
I get i is not defined - remember to declare all your variables
also note that your else if will execute any time that is true, meaning you get the wrong price at the end
maybe moving that
or using something different, using array methods (indexOf for example), makes it easier to solve with a single loop
system
Closed
July 20, 2021, 10:02pm
7
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.