How to calculate average in Javascript using Arrays and Function? [duplicate] - javascript

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) => { ... }"

Related

I'm not getting the expected result of the variable I'm calling [duplicate]

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.

Reduce function only working once in JavaScript code [duplicate]

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());

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

How to add n number of values using Javascript [duplicate]

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)

Why do this returns a non expected result? [duplicate]

This question already has answers here:
Why is [1,2] + [3,4] = "1,23,4" in JavaScript?
(14 answers)
Closed 4 years ago.
So I'm learning about the reduce method and I write this code...
function getSum(x,y){
return x+y
}
var arraySum = function(array) {
return array.reduce(getSum)
};
arraySum([1,[2,3],[[4]],5])
But it actually returns a string of the elements all-together...
I'm actually trying to sum them all... I expected the result to be 15 instead of "12,345"
What's happening? what am I doing wrong?
Your problem is you're adding actual arrays together, not the content within the arrays. Add a counter, and an incrementational variable like i inside the variable arraySum, and call the position of i, incrementing it every time, it should fix your problem.

Categories