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);
Related
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]
I have array
var array = [4,2,6,8,1,6,5,2];
var samNeeded = 20;
as above i need to get how many items need to sum from start of the array to get sum needed
example needed output
var output = [4,2,6,8]
as first four items need to sum up to get the total 20
Not sure this is the best approach, but it works for your example:
const array = [4,2,6,8,1,6,5,2];
const samNeeded = 20;
let sum = 0;
const result = [];
// as long as array still has items and we haven't reached the target sum…
while (array.length && sum < samNeeded) {
result.push(array.shift()); // consume the next item of the input array
sum += result[result.length - 1]; // add it to sum as we go.
}
// it's not clear from your question whether you need the number of items…
console.log(result.length);
// or the items themselves:
console.log(result);
Here is my solution:
const array = [4, 2, 6, 8, 1, 6, 5, 2];
const sumNeeded = 20;
let auxSum = 0;
const res = [];
for (let i = 0; i < array.length; i++) {
if (auxSum >= sumNeeded) break;
auxSum += array[i];
res.push(array[i]);
}
console.log(res);
You could use Array#reduce.
var array = [4,2,6,8,1,6,5,2];
var sumNeeded = 20;
let [res] = array.reduce(([res, sum],curr)=>
[res.concat(sum >= sumNeeded ? []: curr), sum + (sum >= sumNeeded ? 0: curr)],
[[], 0]);
console.log(res);
I've created two functions. One to create 5 random numbers to push them into an array. And another one to sum up the numbers. The random number generator is working and making an array perfectly. But the sum is not accurate. I'm unable to find where the problem is.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
console.log(pushIntoArray());
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
let arr = pushIntoArray();
console.log(sumNum(arr));
Because you are logging a different set of array values and checking the sum of different set of array values.
I have changed your console.log statement.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
let arr = pushIntoArray();
console.log(arr);
console.log(sumNum(arr));
You are not performing the sum on the array that you logged in the console. What you are logging is
console.log(pushIntoArray()); // This is displayed in the console
But then you are generating a ney array by calling
let arr = pushIntoArray();
BUT you are performing the sum on the arr array not the one that is displayed in the console.
console.log(sumNum(arr)); // you did not console.log(arr)
The function works correctly, you are just calling it on the wrong thing.
the function is working correctly but you are logging a different array of random numbers and calculating the sum of a different array.
//Generates 5 random numbers smaller than 10
function pushIntoArray() {
let arr = [];
let number;
for(let i = 0; i < 5; i++) {
number = Math.floor(Math.random() * 11);
arr.push(number);
}
return arr;
}
// this array is different (this is not passed to the sumNum function)
console.log(pushIntoArray());
//Adds the numbers in arr
function sumNum(arr) {
let total = 0;
for(let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
// this array is different
let arr = pushIntoArray();
console.log("sum of array:", arr)
console.log(sumNum(arr));
this is the structure of my array:
arrayParent = [numbers, counter];
numbers = [1,1,1,2,4,5];
counter = [];
what I want to do is counting multiple elements in "numbers" and pushing to "counter" while deleting in the first, in the end it should look like this:
numbers = [1,2,4,5];
counter = [3,1,1,1];
I tried this ( and many many other versions):
for(var y =0; y < arrayParent.length; y++){
for(var x = 0; x < arrayParent[y].numbers.length; x++){
var co = 1;
for(var z = x+1; z < arrayParent[y].numbers.length; z++){
if(arrayParent[y].numbers[x] == arrayParent[y].ans[z]){
co++;
arrayParent[y].numbers.splice(z);
arrayParent[y].counter[x] = co;
}
}
}
}
The result I got:
numbers = [1,2,4,5];
counter = [3,,,];
Any ideas how to solve?
you can try something like:
let numbers = [1,1,1,2,4,5];
let counter = [];
const tmp = numbers.reduce((res, curr) => ({
...res,
[curr]: (res[curr] || 0) + 1
}), {});
numbers = Object.keys(tmp).map(Number);
counter = Object.values(tmp);
console.log(numbers, counter);
so, I created a counter object where keys are distinct numbers and values are their counter
As #nikhil correctly noticed this method will not preserve numbers order, to preserve it, just change JS object to JS Map, the logic is the same:
let numbers = [1,1,1,2,5, 4];
let counter = [];
const tmp = numbers.reduce((res, curr) => res.set(curr, (res.get(curr) || 0) + 1), new Map());
numbers = [...tmp.keys()];
counter = [...tmp.values()];
console.log(numbers, counter);
You can try following
let arrayParent = {numbers : [1,1,1,2,4,5], counter : []};
// This will ensure that the order of elements is same as in the array
let order = [];
// Create an object with key as `number` and counts as its value
let map = arrayParent.numbers.reduce((a,c) => {
if(a[c]) a[c]++;
else {a[c] = 1; order.push(c); }
return a;
}, new Map());
// Set the value of order in numbers
arrayParent.numbers = order;
// Set the counts in counter
order.forEach(o => arrayParent.counter.push(map[o]));
console.log(arrayParent);
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;
}