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

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)

Related

How to to make a varargs statement in javascript [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 1 year ago.
In javascript I am in situation where i need to make variable arguments based on a length of an array, below is an sample code
function getValesList(json){
return getValues(json[0])+getValues(json[1])+getValues(json[2]);
}
function getValues(json1){
let valueList = Object.values(json1);
let valueListPipe = valueList.join("|");
return valueListPipe+lineSeparator;
}
where json is an array of JSON objects and I need to make a pipe delimiter file based on the length of incoming array. How to make it dynamic where I can do like a varargs in JAVA
If you're just passing N arguments of the same type, you can use the rest feature of Javascript for function arguments.
function getValuesList(...json){
return json.map(j => getValues(j)).join("");
}
This allows you go pass any number of separate arguments as in getValuesList(o1, o2, o3, o4) and the json parameter within your function will automatically be an array of however many arguments were passed.

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

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

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 JSON.stringify() works internally? [duplicate]

This question already has answers here:
How to explain callbacks in plain english? How are they different from calling one function from another function?
(34 answers)
Understanding Callbacks
(3 answers)
Closed 4 years ago.
How replacer argument function extract key and value from object value and mapped it to its key and value argument in JSON.Stringify(value, replacer, space) method.
I understood that key of the object become the key parameter of the replacer function and value become value parameter of this function.
let user={name:"anup", age:22};
JSON.stringify(user,function(key,value){
if(typeof value==="string"){
return undefined;
}
return value;
},null);
Here name becoming the key of the replacer function and "anup" becoming the value of the replacer function thats fine, but my question is how this mapping is happening?
Generally we call any method by passing argument in that method call, like
function a(c,d){
// logic
}
a(2,3);
But here in stringify method we are not passing any such thing to the replacer function or callback function, then how it is getting mapped?
Actually, I'm a newbie in javaScript world, so something I'm unable to understand. If you guide me in this regard , I'll be very thankful to you.
How JSON.stringify() works internally?
Thats probably some low level, highly optimized native code. But lets assume it is just a regular JavaScript function instead, that makes things easier. The function would be defined as such:
JSON.stringify = function(toStringify, replacer) {
Now that function has to determine what toStringify is first, e.g.:
if(typeof toStringify === "object") {
In that case, the code has to go over all the objects key/value pairs:
for(let key in toStringify) {
let value = toStringify[key];
Now the code can call the replacer with those pairs:
value = replacer(key, value);
Then a string can be built up as:
result += `"${key}": ${JSON.stringify(value)}`;
Then that result gets returned.

Categories