'How to exit a javascript "for" loop within a "foreach array" loop
I am trying to create a new sets of arrays from the given arrays of phones based on given total cost array at a certain condition when the phones array is looped for the prices.
Fore each of the shared prices, I will like to loop through the phone objects, to test the price by dividing the current share amount with the current phone price. If the division is not more than 120 then the result become the quantity to be used, decimal results is "ceiled" to get an integer.
Then, for that iteration, other variables such as names, model and calculated price are added to respective list. The current phone object is then removed from the phone list and the next iteration for the shared price takes over until the loop is complete.
This code is generating more or less than the expected result and the phone objects is not removed as there are repetition in the outcomes.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<input type="number" id="amount-input">
<button id="calculate" onclick="calculate();">Calculate</button>
<h4>Serial List</h4>
<p class="result" id="serial-view"></p>
<h4>Names List</h4>
<p class="result" id="name-view"></p>
<h4>Models List</h4>
<p class="result" id="model-view"></p>
<h4>Quantity List</h4>
<p class="result" id="quantity-view"></p>
<h4>Price List</h4>
<p class="result" id="price-view"></p>
<h4>Amounts List</h4>
<p class="result" id="amount-view"></p>
<h4>Sub Total</h4>
<p class="result" id="subtotal-view"></p>
<h4>VAT @ 5%</h4>
<p class="result" id="vat-view"></p>
<h4>Gross</h4>
<p class="result" id="gross-view"></p>
<script src="./script.js"></script>
</body>
</html>
JAVASCRIPT
const phones = [
{ name: "BLACKBERRY", model: "BB253", price: 33000 },
{ name: "IPHONE", model: "IPO3", price: 55750 },
{ name: "SAMSUNG", model: "NOTE 4", price: 70000 },
{ name: "NOKIA", model: "WINDOWS", price: 78000 },
{ name: "SAMSUNG", model: "GALAXY A2", price: 93500 },
{ name: "INFINIX", model: "HOT 5", price: 42700 },
{ name: "NOKIA", model: "N347", price: 32550 },
{ name: "TECNO", model: "T154", price: 58500 },
{ name: "LENOVO", model: "Z5S", price: 76250 },
{ name: "NOKIA", model: "9 PURVIEW", price: 195500 },
{ name: "SAMSUNG", model: "NOTE 3", price: 55000 },
{ name: "MOTOROLA", model: "M126", price: 25000 },
{ name: "INFINIX", model: "NOTE 3", price: 55000 },
{ name: "NOKIA", model: "N650", price: 34600 },
{ name: "SAMSUNG", model: "SN330", price: 25800 },
{ name: "IPHONE", model: "IPX", price: 81500 },
{ name: "NOKIA", model: "N3.2", price: 63200 },
{ name: "LG", model: "V30", price: 92300 },
{ name: "GOOGLE", model: "PIXEL 2", price: 61000 },
{ name: "ONEPLUS", model: "5T", price: 49300 },
{ name: "ZTE", model: "AXON M", price: 56000 },
{ name: "NOKIA", model: "N8", price: 58000 },
{ name: "SAMSUNG", model: "J3", price: 48000 }
];
const serialView = document.getElementById("serial-view");
const nameView = document.getElementById("name-view");
const modelView = document.getElementById("model-view");
const qtyView = document.getElementById("quantity-view");
const priceView = document.getElementById("price-view");
const amountView = document.getElementById("amount-view");
const subTotalView = document.getElementById("subtotal-view");
const VATView = document.getElementById("vat-view");
const grossView = document.getElementById("gross-view");
function calculate() {
// window.location.reload(false);
// Initialize Views and Lists
serialView.innerText = "";
nameView.innerText = "";
modelView.innerText = "";
qtyView.innerText = "";
priceView.innerText = "";
amountView.innerText = "";
subTotalView.innerText = "";
VATView.innerText = "";
grossView.innerText = "";
serialList = [];
workingSerialList = [];
ratioList = [];
sharedList = [];
modelList = [];
nameList = [];
qtyList = [];
priceList = [];
// Get amount value from input box
let totalAmount = document.getElementById("amount-input").value;
let actualCost = 100 / 105;
let vatElement = 5 / 105;
const subTotal = (parseFloat(totalAmount) * actualCost).toFixed(2);
const totalVAT = (parseFloat(totalAmount) * vatElement).toFixed(2);
// Get minimum and maximum serial numbers
var min, max = 0;
if (totalAmount < 1000000) {
min = 1;
max = 3;
} else if (totalAmount <= 20000000) {
min = 2;
max = 4;
} else if (totalAmount <= 500000000) {
min = 4;
max = 6;
} else if (totalAmount <= 500000000) {
min = 4;
max = 7;
}
// Get the last list number to work with
let lastNumber = randomLast(min, max);
// Produce and show random serial numbers list
for (let i = 1; i <= lastNumber; i++) {
serialList.push(i);
}
// Create a working serial to prevent original list
for (i = 0; i < serialList.length; i++) {
workingSerialList[i] = serialList[i];
}
// Produce and show random ratio lists
ratioList = shuffleList(workingSerialList);
// // ratioView.innerText = ratioList;
// Calculate and show Ratio List total
const ratioListTotal = ratioList.reduce((currentTotal, ratio) => {
return parseInt(ratio + currentTotal);
}, 0);
// Calculate and display Shared Amounts
ratioList.forEach((ratio) => {
let x = parseInt(ratio) / parseInt(ratioListTotal);
x = (x * subTotal).toFixed(2);
sharedList.push(x);
});
// Set Phone model, name, quantity and price for each amount array
sharedList.forEach((share) => {
// Loop through the phones array to test for a matching price
loop1:
for(let i=0; i < phones.length; i++) {
share = parseFloat(share);
let pricetTest = phones[i].price;
let qtyTest = share / parseFloat(pricetTest);
// If a price is matched
if(qtyTest <= 120) {
// Perform these actions on the current phone loop
let itemQty = Math.ceil(qtyTest);
let itemPrice = parseFloat(share / parseInt(itemQty)).toFixed(2);
modelList.push(phones[i].model);
nameList.push(phones[i].name);
qtyList.push(itemQty);
priceList.push(itemPrice);
// Remove the current phone from the list to prevent it from being tested again
phones.splice(i, 1);
// Stop this loop for the current share price
break loop1;
}
}
});
serialView.innerText = serialList;
nameView.innerText = nameList;
modelView.innerText = modelList;
qtyView.innerText = qtyList;
priceView.innerText = priceList;
amountView.innerText = sharedList;
subTotalView.innerText = subTotal;
VATView.innerText = totalVAT;
grossView.innerText = parseFloat(totalAmount).toFixed(2);
}
// Function to get random number between ranges
function randomLast(m, x) {
m = Math.ceil(m);
x = Math.floor(x);
return Math.floor(Math.random() * (x - m + 1) + m);
}
// Random number generator
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// Shuffler function
function shuffleList(array) {
array.sort(() => Math.random() - 0.5);
return array;
}
I am getting fine results until the input is more than a few millions which is weird.
Solution 1:[1]
EDIT : So if I understand what you want to do :
const phones = [
{ name: "BLACKBERRY", model: "BB253", price: 33000 },
{ name: "IPHONE", model: "IPO3", price: 55750 },
{ name: "SAMSUNG", model: "NOTE 4", price: 70000 },
{ name: "NOKIA", model: "WINDOWS", price: 78000 },
{ name: "SAMSUNG", model: "GALAXY A2", price: 93500 }
];
const modelList = new Set([]);
nameList = new Set([]);
qtyList = new Set([]);
priceList = new Set([]);
const sharedPrices = [200000, 150000, 300000, 250000];
for (const sharedPrice of sharedPrices) {
phones.forEach(phone => {
const { price } = phone;
const qty = Math.floor(sharedPrice / price);
if (qty <= 120) {
const { model } = phone;
const { name } = phone;
modelList.add(model);
nameList.add(name);
qtyList.add(qty);
priceList.add(price);
}
})
}
console.log(modelList)
console.log(nameList)
console.log(qtyList)
console.log(priceList)
Output :
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

