I am new to javascript and I am learning about looping through arrays. Anyways I have an array of prices and an array of names. I want the the output to be: "Name:Price". So for example: Pound: 454 Half Pound: 227 Quarter Pound: 114 etc....
For some reason however the output that I am getting is a repeat of each name with each price next to it as you can see in the snippet below. Thanks for the help in advance. :)
const salePrices = [454,227,114,28,14,7,3.5];
const names = ['Pound','Half-Pound','Quarter Pound','Ounce','Half Ounce','Quarter Ounce','Eighth'];
for (let i = 0; i < salePrices.length; i ){
for(let x = 0; x < names.length; i ){
console.log(`${names[x]}:${salePrices[i]}`)
}
}
CodePudding user response:
You don't need two loop for that. One loop would be enough to get the index
and then get the names
and salePrices
from it as:
const salePrices = [454, 227, 114, 28, 14, 7, 3.5];
const names = [
"Pound",
"Half-Pound",
"Quarter Pound",
"Ounce",
"Half Ounce",
"Quarter Ounce",
"Eighth",
];
for (let i = 0; i < salePrices.length; i ) {
console.log(`${names[i]}: ${salePrices[i]}`);
}
CodePudding user response:
Yes that's because inner loop is running completely per one iteration of outer loop. So for every sales price, names are running full.
If both arrays are already in correct order, you can just use one for loop.
const salePrices = [454, 227, 114, 28, 14, 7, 3.5];
const names = [
"Pound",
"Half-Pound",
"Quarter Pound",
"Ounce",
"Half Ounce",
"Quarter Ounce",
"Eighth",
];
for (var i = 0; i < salePrices.length; i ) {
console.log(names[i] ":" salePrices[i])
}
CodePudding user response:
I assume that you meant to increment x
in the for loop instead of i
.
In the first for loop you were iterating through the salePrices
. Therefore salePrices[i]
will get you 454 -> 227 -> 114 -> 28 -> 14 -> 7 -> 3.5
In the second for loop you were iterating through the names
. Therefore names[x]
will get you 'Pound' -> 'Half-Pound' -> 'Quarter Pound' -> 'Ounce' -> 'Half Ounce' -> 'Quarter Ounce' -> 'Eighth'
However, the second for loop is nested inside the first for loop. Therefore, all the names
were iterated for each sales prices. Ex:
When i=0
, it will print:
Pound:454
Half-Pound:454
Quarter Pound:454
etc...
If you were sure the length of names
and salePrices
are the same. You can use decpk's answer.
You can also make them an object instead with names
as key and salePrices
as value (which is probably more fitting in this use case).
const products = {
"Pound": 454,
"Half-Pound": 227,
"Quarter Pound": 114,
"Ounce": 28,
"Half Ounce": 14,
"Quarter Ounce": 7,
"Eighth": 3.5,
};
for (const [name, price] of Object.entries(products)) {
console.log(`${name}: ${price}`);
}