I have the following code
function getNumberWithCommas(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
var price = [
6599, 7659, 899, 569, 899, 279, 219, 1797, 3999, 2769, 599, 1349, 2149, 219,
219, 519, 2499, 2949, 5149, 7689, 15999,
];
for (let i = 0; i < 20; i++) {
var productPrice = document.createElement("span");
productPrice.className = "price";
productPrice.setAttribute("id", `price-id-${i}`);
var calculatedPrice = price[i] * quantities[i];
productPrice.textContent = `R$ ${getNumberWithCommas(calculatedPrice)},00`;
precoTotalDiv.appendChild(productPrice);
var totalPrice = [];
totalPrice.push(calculatedPrice);
console.log(totalPrice);
}
It dynamically creates prices for products based on their quantity in the cart and their price. I would like to save these values (calculatedPrice) inside an array so I can get a total price (sum of all the prices) at the bottom of the cart.
It is adding calculatedPrice to totalPrice[], but it only adds one value, the length of the array remains one. Once I click another product, calculatedPrice gets overwritten with another products price.
I would like to get a sum of all the prices generated, not the sum of only one product.
just move let totalPrice = [] to outside of the loop:
Because when you put totalPrice inside the loop and it will be reset value on each loop
var totalPrice = [];
for (let i = 0; i < 20; i++) {
var productPrice = document.createElement("span");
productPrice.className = "price";
productPrice.setAttribute("id", `price-id-${i}`);
var calculatedPrice = price[i] * quantities[i];
productPrice.textContent = `R$ ${getNumberWithCommas(calculatedPrice)},00`;
precoTotalDiv.appendChild(productPrice);
totalPrice.push(calculatedPrice);
}
console.log(totalPrice);
This is because you're creating a new array on each loop
Declare your array outside of the loop first:
var totalPrice = [];
for (let i = 0; i < 20; i++) {
var productPrice = document.createElement("span");
productPrice.className = "price";
productPrice.setAttribute("id", `price-id-${i}`);
var calculatedPrice = price[i] * quantities[i];
productPrice.textContent = `R$ ${getNumberWithCommas(calculatedPrice)},00`;
precoTotalDiv.appendChild(productPrice);
totalPrice.push(calculatedPrice);
console.log(totalPrice);
}
You can save the values generated by a for loop inside an array in JavaScript by using the push method of an array. Here's an example:
// Initialize an empty array
var result = [];
// Use a for loop to generate values
for (var i = 0; i < 5; i++) {
// Push the generated value to the array
result.push(i);
}
// Print the final array
console.log(result);
This will output:
[0, 1, 2, 3, 4]
Related
1.This code shows NaN
2.I changed subaray[1] to the number but shows NaN
3. please help to solve this
let products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99' ];
for(let i = 0; i < products.length; i++) {
let subArray = products[i].split(':');
let name = subArray[0];
let price = Number(subArray[1]);
let total;
total += price;
console.log(total) //total shows NaN
}
You just need to move the total out of the loop, you're creating a new total variable every time your loop iterate. You should also assign a number to the total, so you don't sum a undefined with a number.
let products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99' ];
let total = 0;
for(let i = 0; i < products.length; i++) {
let subArray = products[i].split(':');
let name = subArray[0];
let price = Number(subArray[1]);
total += price;
console.log(total) //total shows NaN
}
typicaly use case for array reduce() method
let products =
[ 'Underpants:6.99'
, 'Socks:5.99'
, 'T-shirt:14.99'
, 'Trousers:31.99'
, 'Shoes:23.99'
]
let total = products.reduce((a,c)=> a +Number(c.split(':')[1]), 0).toFixed(2)
console.log(total)
You need to initialize let total = 0;
let products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99' ];
let total = 0;
for(let i = 0; i < products.length; i++) {
let subArray = products[i].split(':');
let name = subArray[0];
let price = Number(subArray[1]);
total += price;
console.log(total) //total shows NaN
}
Use the array methods available for such tasks, in this case Array.prototype.reduce:
let products = ['Underpants:6.99', 'Socks:5.99', 'T-shirt:14.99', 'Trousers:31.99', 'Shoes:23.99'];
let total = products.reduce((acc, val) => acc + Number(val.split(':')[1]), 0);
console.log(total);
Array.prototype.reduce, as the name says, is the right function whenever you need to reduce an array to a single value.
Using Array.prototype.reduce()
const products = [
"Underpants:6.99",
"Socks:5.99",
"T-shirt:14.99",
"Trousers:31.99",
"Shoes:23.99",
];
const total = products.reduce(
(amount, current) => amount + parseFloat(current.replace(/[a-z-:]/gi, "")),
0
);
console.log(total);
I have this array of objects to count element frequency in another array using for loop which prints correct output.
counts = {};
counter = 0;
counter_array = [50,50,0,200]; //this is just for example, this array is filled dynamically
for (var x = 0, y = counter_array.length; x < y; x++) {
counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1;
}
console.log('FREQUENCY: ',counts); //outputs FREQUENCY: {50:2, 0:1, 200:1}
There is another array of arrays:
holder_text_array = [["a",50,0],["b",0,0]]; //example of dynamically filled array
var p = "a";
var i = 0;
while(i < holder_text_array.length){
if (holder_text_array[i][0]==p) {
var s = counts[holder_text_array[i][1]];
console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0
console.log('frequency: ',counts[s]); //prints undefined
counter = counts[s];
}
i++;
}
The array of arrays "holder_text_array" consists of elements whose frequency I need to get in the while loop. Can someone tell me where am I wrong?
The frequency is stored in s not in counts[s]
You're logging counts[s] where var s = counts[holder_text_array[i][1]];
You've already got the element from counts in s. Just log the value of s
Apart from that the function works!
counts = {};
counter = 0;
counter_array = [50,50,0,200]; //this is just for example, this array is filled dynamically
for (var x = 0, y = counter_array.length; x < y; x++) {
counts[counter_array[x]] = (counts[counter_array[x]] || 0) + 1;
}
console.log('FREQUENCY: ',counts); //outputs FREQUENCY: {50:2, 0:1, 200:1}
holder_text_array = [["a",50,0],["b",0,0]]; //example of dynamically filled array
var p = "a";
var i = 0;
while(i < holder_text_array.length){
if (holder_text_array[i][0]==p) {
var s = counts[holder_text_array[i][1]];
console.log('Element: ', holder_text_array[i][1]); //prints 50 for i = 0
console.log('frequency: ', s); // CHANGED THIS TO JUST `s`
counter = counts[s];
}
i++;
}
You could take a recursive approach and call the count function again for (nested) arrays with the same counts object.
The result contains the counts of each element.
function getCounts(array, counts = {}) {
for (let i = 0; i < array.length; i++) {
const value = array[i];
if (Array.isArray(value)) {
getCounts(value, counts);
continue;
}
if (!counts[value]) counts[value] = 0;
counts[value]++;
}
return counts;
}
console.log(getCounts([["a", 50, 0], ["b", 0, 0]]));
I figured out the problem. Issue is in initialization.
I changed the following:
var s = counts[holder_text_array[i][1]];
counter = counts[s];
It works this way:
var s = holder_text_array[i][1];
counter = counts[s];
I stored variables in an array. Now I need to extract the variables with the highest value and store them in another array.
This is for a javascript program running on a wix website for my daughter.
var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;
var points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}],
The variables are already in ascending order. So I need the program to figure out that mistral, saya and luna tied at the top position, then to extract these 3 variables (name of the variables + respective values) and store them in another array. If I had a case where a single variable had the highest value, then a single variable would be stored in the new array.
One way is to find the biggest value first with .map and .reduce working together. Then we can get the objects from the points array that have their first properties with value of maxValue and push it to a separate array newArray.
var maxValue = points
.map(function(obj){ return obj[Object.keys(obj)[0]]; }) //map into array of numbers
.reduce(function(a, b){ return Math.max(a, b);}); // return max value
var newArray = points // filter objects with first prop = maxValue
.filter(function(obj){ return obj[Object.keys(obj)[0]] === maxValue; });
Result will be:
[{mistral: 4}, {saya: 4}, {luna: 4}]
Since your array is ordered, you already know the maximun value is at the last position of the array. So first, you can get this value, and then you can use this value to filter elements whose values are equal to this one:
var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;
var points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}];
// Since array is ordered, highest value is at the last position.
// So, we can get it like this:
let maxVal = Object.values(points[points.length - 1])[0];
console.log(maxVal);
// Now, filter the array with the highest elements
let highest = points.filter(x => Object.values(x)[0] === maxVal);
console.log(highest)
In the case your initial array is not ordered as you have mentioned, then you can proceed with something like this:
var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;
var points = [{saya}, {rodeo}, {mistral}, {balthazar}, {luna}, {kiara}, {calypso}];
// Since array is not ordered, we need to get highest value.
// So, we can get it like this:
let maxVal = points.reduce((max, v) => Math.max(Object.values(v)[0], max), null);
console.log(maxVal);
// Now, filter the array with the highest elements
let highest = points.filter(x => Object.values(x)[0] === maxVal);
console.log(highest)
Here is the ES6 way of doing things. The edge case of the list not being in order is taken care of, so the highest values can be anywhere. You can also modify it to get the smallest values. If you have any questions about the code just ask and I will respond.
const kiara = 1;
const rodeo = 3;
const calypso = 3;
const balthazar = 3;
const mistral = 4;
const saya = 4;
const luna = 4;
function getNamesWithHighestPoints(points) {
const hash = {};
for(let i = 0; i < points.length; i++) {
let point = points[i];
let name = Object.keys(point)[0];
let score = Object.values(point)[0];
if(hash[score] === undefined) {
hash[score] = [point];
}
else {
hash[score].push(point);
}
}
let biggestScore = 0;
Object.keys(hash).forEach(pointKey => {
if(biggestScore < pointKey) {
biggestScore = pointKey;
}
});
return hash[biggestScore];
}
const points = [{kiara}, {rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna}];
console.log(getNamesWithHighestPoints(points));
Solution Below. There would be a way to do this with less code, but this will get the job done for you. One thing to remember, for in loops are your friend when working with objects.
var kiara = 1;
var rodeo = 3;
var calypso = 3;
var balthazar = 3;
var mistral = 4;
var saya = 4;
var luna = 4;
var points = [{rodeo}, {calypso}, {balthazar}, {mistral}, {saya}, {luna},{kiara}];
var maxNumberArray = [];
var maxNamesArray = []; // ADDED THIS LINE
var max;
for(var char in points){
for(var name in points[char]){
if(!max){
max = points[char][name];
} else {
if(max < points[char][name]){
max = points[char][name];
}
}
}
}
for(var char in points){
for(var name in points[char]){
if(points[char][name] === max){
maxNumberArray.push(points[char]);
maxNamesArray.push(name); // ADDED THIS LINE
}
}
}
console.log(JSON.stringify(maxNumberArray));
console.log(maxNamesArray); // ADDED this LINE
:)
Our array
This is the dynamic array,every data array have different number of elements.
how can i find index based average and then add final result to last index of the series array.
series[
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
]
Our try :
var data = [];
var sum = 0;
var newseries = {};
for (var i = 0; i < series.length; i++) {
for(var j= 0;j<(Math.max(series[i].data.length);j++){
var rmv_undified=series[i].data[j];
if(rmv_undified!=undefined){
sum+=parseFloat(rmv_undified)/series.length;
}
}
data.push(sum);
};
newseries.data = data;
series.push(newseries);
but i got result like this :
series[
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
{data:[7,17.33,3.66]}
// wrong result of above code working 1+2+3+5+10/3 = 7,6+9+10+6+10+6+5/3 = 17.33,2+5+4/3 = 3.66
]
I need result :
series[
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
{data:[3,5.33,5.66,3.66,6.66,2,1.66]} // index based average
]
Find the max length of all arrays first, then iterate through series and average nth item each iteration until n is max length.
let series = [
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
];
const maxl = [].reduce.call(series, (max, obj) => Math.max(obj.data.length, max), -1)
let avgs = [];
for (let i = 0; i < maxl; i++) {
let avg = [].reduce.call(series, (acc, n) => acc + (n.data[i] ? n.data[i] : 0), 0)/series.length;
avgs.push(avg);
}
series.push({data: avgs});
console.log(series);
You have to loop over j first, and for fixed j iterate over the different arrays in series.
Alternatively you can keep your code and change
sum+=
to
sum[j]+= and initialize this variable as an array. Then you have to push accordingly.
Try below solution. We have to iterate first through series array and then through each data array.
var series = [
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
];
var averageArray=[];
series.forEach(function(obj){
var sum=0;
obj.data.forEach(function(arrValue){
sum = sum + arrValue;
});
averageArray.push(sum/obj.data.length);
});
series.push({data:averageArray});
console.log(series)
First, find the max length of the data array. Then iterate through each item of the series array to find the average. punkr code
function avgMultipleArrary(arr) {
var len = arr.length;
var sum = 0;
var maxLen=arr[0].data.length;
var resultArray = [];
for(var i=0;i<len;i++){
arr.map(function(arrEle,index){
if (maxLen < arrEle.data.length) {
maxLen = arrEle.data.length;
}
})
}
for(var i=0;i<maxLen;i++){
arr.map(function(arrEle,index){
var data = arrEle.data;
if(data[i] !== undefined)
sum +=data[i];
})
var avg = Number((sum/len).toFixed(2));
resultArray.push(avg)
sum =0;
}
arr.push({data:resultArray});
return arr;
}
I am trying to develop a calculation and I need to make a for loop that when it's calculated I need to add 3 up,
the code I use is:
var fields = [fieldname140, fieldname879, fieldname886],
result = 0.00;
for(var i = 1, h=fields.length; i<h; i++)
{
if(ABS(1-fields[i])<ABS(1-result)) result = fields[i];
}
return result;
is there a possibility to do so?
function calculate() {
var fields = ['fieldname140', 'fieldname879', 'fieldname886']; var result = '';
var newFields = [];
for(var i = 0; i < fields.length; i++){
var index = fields[i];
var indexName = index.substring(0, 9);
var indexVal = parseInt(index.substring(9));
result = indexName + (indexVal + 3);
newFields.push(result);
//console.log(result);
}
//console.log(newFields);
return newFields;
}
Call this calculate function and get new fields array with increment.