Array.reduce() stacking numbers rather than summing them? [duplicate] - javascript

This question already has answers here:
Sum of a javascript array returns a string concatenation of all the numbers [closed]
(3 answers)
Closed 3 years ago.
I'm trying to reduce an array of numbers into the sum of all the numbers combined. At the moment I'm using Array.reduce to try and achieve this, but what I'm finding is that this function only stacks the array's values to create one massive number rather than summing them all together.
// Function used to get the sum of all numbers in array
function getSum(total, num){
return total + num;
// Reduce Var
var easternSum = scoreEastern.reduce(getSum);
// Dynamic array based on user input
var scoreEastern = dataSet
.filter(scoreEastern => scoreEastern.Course === 'eastern')
.map(({Score}) => Score);
// Empty array that scoreEastern var is assigned to
var dataSet = [];
Because my array is dynamic, it's based on what the user inputs into a form, there's no set array. But let's say the array is:
var scoreEastern = [10, 20, 30]
The reduce var easternSum will result in the number 102,030. What I want is 60.

I think maybe scoreEastern doesn't have the data that you expect all the time? You mentioned that it is dynamic. This snippet appears to work for the use case you posted in your question.
const scoreEastern = [10, 20, 30];
console.log(scoreEastern.reduce((prev, curr) => prev + curr));

Related

Is there any way to plus multi array number in javascript? [duplicate]

This question already has answers here:
How to calculate the sum of multiple arrays?
(6 answers)
Closed 1 year ago.
I have an array. With each item in array is an array number. And the length of each array is the same. For example:
var data = [[1,2,4,1], [2,2,1,3], [1,1,2,2], ...]
And the result I want to have:
=> res = [4, 5, 7, 6]
res is the result of adding arrays according to the corresponding index. And of course my data may also contain lots of items.
I have referenced through the lodash.unzipWith. But it doesn't seem viable. With any advice. please let me know. Sorry for my weak English
You can use reduce and write something like this, without lodash or anything
const data = [[1,2,4,1], [2,2,1,3], [1,1,2,2]]
const sumArrs = (arrs) => {
return arrs.reduce((prev, curr) => {
return curr.map((num, i) => num + (prev[i] || 0))
}, [])
}
console.log(sumArrs(data))

How to take digits of PI as strings and return an array of the digits as numbers? [duplicate]

This question already has answers here:
Convert string array to integer array
(4 answers)
Closed 4 years ago.
I need to take the first 1000 digits of pi as strings in an array and return them into a new array as digits:
from this: ["1","4","1","5","9","2"...] (the full array of numbers is already provided in my assignment)
to this: [1, 4, 1, 5, 9, 2...]
I've tried creating a new variable with an empty array and using the .join method but when I console log it it returns the an empty array.
const strNums = ["1","4","1","5","9","2"...]
const newArray = [];
const integers = strNums.join(newArray);
console.log(newArray);
const input = ["1","4","1","5","9","2"];
const output = input.map(Number);

Modify all but first element of multidimensional array [duplicate]

This question already has answers here:
How to round all the values in an array to 2 decimal points
(4 answers)
How can I skip a specific Index in an array in a for loop javascript
(1 answer)
Closed 5 years ago.
Let's say there is this array of arrays:
theArray = [["name1", 12.23423, 54.243, 6.23566, 5675.552, ...],
["name2", 345.8655, 92.9316, ..],
["name3", 99.56756, 52.988, 3.09889, ...],
...
];
Each sub-array starts with a string and it is followed by numbers. My aim is to reduce the numbers to a shorter form.
I know that this can be done using .toFixed(2) in order to have only two digits after the dot by I don't know how to access them because of the string in the front.
I want them to remain as numbers because I must use them as data for a chart.
Do you have any suggestions?
You could keep the value of the first item.
var array = [["name1", 12.23423, 54.243, 6.23566, 5675.552], ["name2", 345.8655, 92.9316], ["name3", 99.56756, 52.988, 3.09889]],
result = array.map(a => a.map((v, i) => i ? +v.toFixed(2) : v));
console.log(result);
Simple solution by just using two nested for loops with Index 0 and Index 1.
theArray = [["name1", 12.23423, 54.243, 6.23566, 5675.552],
["name2", 345.8655, 92.9316],
["name3", 99.56756, 52.988, 3.09889],
];
for(var i=0;i<theArray.length;i++) {
for(var k=1;k<theArray[i].length;k++) {
theArray[i][k] = parseFloat(theArray[i][k].toFixed(2));
}
}
console.log(theArray);

Iterate over an array and get the transformed array as a result [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Return array value with forEach() [duplicate]
(1 answer)
Closed 5 years ago.
So there are a lot of questions about iterating over an array, but I found none that says how to get the transformed array back as the left side variable. I can always do a standard for loop with indicies but I was wondering if I could use something like a .foreach that would return a transformed array.
Psedo example: I have an array points which are made up of an object Phaser.Point
Such that I can write the following code
x = new Phaser.Polygon(points.foreach(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
new Phaser.Polygon takes an array of Phaser.Point objects
In this case, you may want to use Array.prototype.map(). Here is an example from MDN:
var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
In your case:
x = new Phaser.Polygon(points.map(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
References:
Array.prototype.map()
You can use Array.map. Array.map returns new array.

Calculating The Average Value Of Array Elements In Java Script? [duplicate]

This question already has answers here:
Finding the average of an array using JS [duplicate]
(9 answers)
Closed 7 years ago.
I Want To Calculate Average Value Of Array Elements Using Java Script. I am an beginner in Java Script, So Please Give me the easiest & understandable code
Assuming that all items in your array are numbers, loop through them, and sum them. Once you have a sum of all items, divide this figure by number of items (your_array.length) and then you'll get your average.
Show your existing code, what you have done so far?
Not tested, pseudo code:
var array = [1, 6, 43, 2, 8];
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += parseInt(array[i]);
}
if (array.length > 0) {
console.log('Average is ' + (sum / array.length));
}

Categories