This question already has answers here:
How to call reduce on an array of objects to sum their properties?
(23 answers)
Closed 2 years ago.
I currently have to functions which use the Array.reduce method but only the first function works.
let profit = incomes.reduce((a,b) => a.getAmount() + b.getAmount());
Where a = a custom BudgetItem class with the method getAmount. I am wondering if this is a common JS thing or if I am doing something wrong.
Please note I have checked with the debugger and entering this line I have the same data in both methods.
According to mozilla the first parameter in Array.reduce() is the accumulator (the current sum) and the second is the current value from the array
arr.reduce(callback( accumulator, currentValue, [, index[, array]] )[, initialValue])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
So if you are trying to total the value from an array of BudgetItem you will want something like:
let profit = incomes.reduce((currentTotal, curremtIncome) => currentTotal + curremtIncome.getAmount());
Related
This question already has answers here:
How to compute the sum and average of elements in an array? [duplicate]
(35 answers)
Closed 1 year ago.
enter image description here
Hi, I just learnt about Javascript Functions and would like to know the method for finding out average using Arrays and Functions in JS.
I have linked a screenshot of my code, can you please help me?
const scores = [60, 75, 21, 43];
const avg = scores.reduce((accumulator, currentValue) => accumulator + currentValue)/scores.length;
console.log(avg);
The Reduce function when used on an array will iterate over its entirety, with each iteration having access to a Accumulator (A single variable shared across all iterations) and a CurrentValue (Represents the current interation value). Using this you can add all the values together and divide the result by the array's length.
This can also be replaced with a function,
"(accumulator, currentValue) => ..." is a lambda expression and is basically just shorthand for
"function funcNameHere(accumulator, currentValue) { ... }"
Lambda expressions can also declare a body just like a normal function.
"(param) => { ... }"
This question already has answers here:
Does .sort function change original array?
(6 answers)
Why A and B are equal after sort()?
(3 answers)
How can you sort an array without mutating the original array?
(11 answers)
Closed 1 year ago.
I came across something strange. Here two variables which store two differents results:
const membersSortedByCurrentStageTotalPoints = teamMembers.sort((a, b) => compareRanking(a,b,currentIndex));
const membersSortedByRankingType = teamMembers.sort((a, b) => compare(a, b, "points"))
But when I'm using the variable membersSortedByCurrentStageTotalPoints I get the results of the variable membersSortedByRankingType.
Anyone would know why ?
From the MDN documentation for sort:
Return value
The sorted array. Note that the array is sorted in place, and no copy
is made.
The two variables both have the same value: A reference to the same array.
This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 2 years ago.
I have one doubt here that I need to pass n nos of values as argument and calculating the total sum of it using Javascript. I am explaining some sample code below.
function add(a,b,c) {
return a+b+c;
}
var data =add(5,6,7);
console.log(data)
Here I am passing only 3 arguments to the function but I need to pass n numbers of argument to the function like inside function its known how many values have passed as argument and final I need the total sum and return it.
You can either reduce over it to sum all if you want to write it in a functional way like
function add(...numbers) {
return numbers.reduce((acc,no) => return acc + no),0);
}
or by using arguments keyword knowing it's only available if the function is normal function, not an arrow function.
here's a ref https://stackoverflow.com/a/38567145/1888435
also, arguments aren't an array it's an array-like and if you checked typeof arguments it will give you object.
As #slappy said you can get parameters as array
function add(...numbers){
// Values reach as array
console.log(numbers)
// Here you should use array inner functions
return numbers.reduce((sum,value) => sum+value, 0)
}
let data = add(5,6,7);
console.log(data)
This question already has answers here:
What is the difference when we use array names instead of spread operator?
(3 answers)
Closed 4 years ago.
Consider a scenario where in you are trying to iterate over a const array.
Would there be any difference between
[...arr].forEach((elem) => {
// your operations
});
and
arr.forEach((elem) => {
// your operations
});
Can these two be used interchangeably?
It will make a copy of the array. If the callback function would use the array parameter and it would modify it, that would make a difference. E.g.:
[...arr].forEach((val, i, a) => a.push(val))
If arr is not an array but an array-like, it will turn it into an array and thereby allow you to forEach over it. E.g.:
[...document.getElementsByTagName('p')].forEach(p => console.log(p))
This question already has answers here:
How does the Math.max.apply() work?
(5 answers)
Closed 7 years ago.
Say for example I want the largest number out of an array of numbers.
var numbers = [54,34,76,33,87,12,76,92,44,93,23];
I want to be able to use Math.max() to find the largest number without using eval.
So, I want to be able to pass an array of parameters to a function. The array's length can change, so Math.max(numbers[0],numbers[1]...) won't work.
Is there any way I can do this?
You can use the .apply() method:
var max = Math.max.apply(Math, numbers);
The .apply() method is a property of Function.prototype and so is available on all function instances. Its first argument is used as the value of this in the function to be called, and the second argument should be an array that will be used as the list of parameter values.
In my example above I used Math as the value for this, because that's what this will be in a typical invocation of Math.max, but (on my installation of Firefox at least) Math.max.apply(null, numbers); works too.