sum object from multi arrays in app script - javascript

I'm using app script
I have Return array from API by this code :
const price= jsonResponce.price.map(obj => [obj[0],obj[1]]);
Give me [[30.56, 1.014], [50.44, 1.019], [10.35, 1.081], [10.34, 1.115], [10.40, 2.006]]
Not this array can be has 1000 array or large
Now I want to sum all object in obj[0] by using this code :
I use to method to see the deference but nothing work
var first= [];
var second= 0;
price.forEach(function(obj){
first+= obj[0];
second+= obj[1];
});
Logger.log(first);
Logger.log(second);
But Give me result like that: first Logger.log(first);
30.5650.4410.3510.3410.40
second Logger.log(second); : this method add number 0 after any obj
01.01401.01901.08101.11502.006
Any idea for this problem
30.56+50.44+10.35+10.34+10.40
I need result as : 112.09

Your code works fine for me, after minimal corrections:
const price = [[30.56, 1.014], [50.44, 1.019], [10.35, 1.081], [10.34, 1.115], [10.40, 2.006]]
var first = 0; // <-- here
var second = 0;
price.forEach(obj => {
first += +obj[0]; // <-- here
second += +obj[1]; // <-- here
});
console.log(first); // --> 112.09
console.log(second); // --> 6.2349
You can get four digits after dot this way:
var a = 1.23456789;
var b = 1234.56789;
var c = 16643.59000000003
const dot1000 = x => Math.round(x*10000)/10000;
console.log(dot1000(a));
console.log(dot1000(b));
console.log(dot1000(c));
Another implementation (with zeros at the end)
var a = 1.23456789
var b = 1234.56789
var c = 16643.59000000003
const dot1000 = x => parseInt(x) + '.' + (x+.00001+'').split('.')[1].slice(0,4)
console.log(dot1000(a))
console.log(dot1000(b))
console.log(dot1000(c))
Update
Modern JavaScript (ES2017) can add zeros this way:
console.log('123'.padEnd(5,'0')); // 12300
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

numbersInArray = price.flat()
let sum = 0
numbersInArray.forEach( number => sum += number)

Using Array.prototype.reduce() method, this becomes very easy:
const result = arr.reduce((total, el)=> {
return total + el[0] + el[1] // el = [a, b]
}, 0)
console.log(result) /// 118.325
Let me know in the comments if this is what you want or you want any improvements

You are adding the array in which each number (both obj[0] and obj[1] values) is treated as String type. So that's why they are not added like numbers but concatenated. First convert the String Type into Number. Then your problem will be resolved.
As I don't know about the used API. So I could not give answer with API response included. But I am giving you code where I do some changes but just look at the praseFloat() method that I used.
const Api_Response_Array = [["30.56", "1.014"], ["50.44", "1.019"], ["10.35", "1.081"], ["10.34", "1.115"], ["10.40", "2.006"]];
var first= 0;
var second= 0;
Api_Response_Array.forEach(function(){
first+= parseFloat(Api_Response_Array[0][0]);
second+= parseFloat(Api_Response_Array[0][1]);
});
document.write(first + "<br>");
document.write(second);
Just use praseFloat method inside function used within forEach loop. It will convert the string into number.

Related

Extract a value from a Custom Javascript array when it's a component of a string value within an array

I'm looking to extract the values 'adult' and '2ndclass' from this custom javascript array in separate javascript variables for each value. Anyone has any ideas on how to do this?
In the following case, there are 2 products added to cart but I would like to have the flexibility to always grab any existing values for each product that is added to cart regardless of the amount added. Is that possible?
[
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**',
'pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**'
]
Thank you in advance for your help
You can also use RegExp to get those values out.
var arr = [
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**adult/2ndclass**",
"pass/DE-NO-RS-BE-FI-PT-BG-DK-LT-LU-HR-LV-FR-HU-SE-SI-ME-SK-GB-IE-MK-EE-CH-GR-IT-ES-AT-CZ-PL-RO-NL-TR-BA/**youth/2ndclass**"
];
var results = [];
for (var i=0; i < arr.length; i++) {
var matches = arr[i].match(/\*\*(.+)\/(.+)\*\*/);
if(matches && matches.length >= 3)
results.push([matches[1], matches[2]]);
}
console.log(results);
You can try the code here https://jsfiddle.net/p84eftL7/1/
First of all i didn't get your question completely. But as far as i can understand you want those 2 values at the end of the strings from an array. You can try something like this
var a, b;
for(s in YOUR_ARRAY){
[...other, a, b] = YOUR_ARRAY[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
Let me explain myself, Firstly you would require to iterate over your array thats why we have a 'for' loop here. Then for each string which is given by 'YOUR_ARRAY[s]' you are splitting the string with '/' as a delimiter. Rest of the thing is pretty simple.
For your reference go through these links
https://www.w3schools.com/js/js_loop_for.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
UPDATE:
As mentioned in the comments. If you want to have a function for this then
function processValues(arr){
var a, b;
for(s in arr){
[...other, a, b] = arr[s].split("/");
console.log(a, b);
//Do whatever you want to do with a,b
}
}
processValues(YOUR_ARRAY);
In the end what I did was the following
As I had to reference back to the name of the variable I used the following to slice up the array so I could reference that using index numbers for the values I needed to retrieve:
function() {
var myStringArray = {{MY_ARRAY}};
var arrayLength = myStringArray.length;
var output = []
for (var i = 0; i < arrayLength; i++) {
var string = myStringArray[i].split("/",4)
/*pull index 2 and 3 from string and convert to string*/
output.push(string)
}
return output
}
After that I had to loop the new array that was being pushed out of the info as mentioned above
Since I only needed to split up particular indices from that NEW_ARRAY_2, I used the following to do that
function() {
var products = {{NEW_ARRAY_2}};
var arr = []
for (var i=0; i < products.length; i++) {
var prod = products[i];
var matches = prod[2];
arr.push(matches);
}
var list = arr.join(', ')
return list
}
SAMPLE RETURN for 2 products: 'adult, youth'
Thank you for your support

How to find max number from an array, but from selected elements only in javascript

This is my array from which I want to find max.
number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
console.log((Math.max(...number[abc]));
Here the output is 444, and it's working fine. But now, I want to select max from selected indexs. I am storing those indexes in this array.
available = [0,2,3];
Now, index 0,2,3 of number[abc] are 43,34, 6
And I want 43 to be displayed, because it is the max from selected indexes.
How can I do it?
Map the indicies to the values, and then call Math.max on those values:
const number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
const available = [0,2,3];
const availableValues = available.map(i => number.abc[i]);
console.log(Math.max(...availableValues));
You can create a reusable function that will have a custom logic to check the highest number instead of using Math.max(). Using reusable function will help you to scale the code without duplicating the logic.
var available = [0,2,3];
var number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
function getHighest(available, number){
var index = available[0];
var highest = number[index];
for(var i=1; i<available.length; i++){
index = available[i];
if(highest < number[index]){
highest = number[index];
}
}
return highest;
}
var highest = getHighest(available, number['abc']);
console.log(highest);
You can also achview this by filtering the number.abc array.
const number = {"abc": [43,4,34,34,6,444], "dsfsd":[324,324,32,43,34,2] };
const available = [0,2,3];
const filtered = number.abc.filter((num, idx) => available.includes(idx));
console.log(Math.max(...filtered));

Naming; dynamically create a variable in javascript

To avoid a javascript heap problem, I use multiple arrays: family1, family2,family3 ..., dogs1, dogs2, dogs3 ... Use example: 'family1 and dogs1', or 'family132 and dogs132' to create a new array 'results'.
How do I pass the "id" correctly
let id = 'value here'
this.family + id
this.dogs + id
So far my str itself is pushed int the new array: t-h-i-s-.-f-a-m-i-l-y-1
for (let i = +0; i < +20; i++) {
const id = 1;
let str = 'this.family'+id; // ?
let str = 'this.dogs'+id; // ?
console.log(str);
const result = {
familyType: str[i], // behavior: t-h-i-s-.-f-a-m-i-l-y-1
protocol: this.dogs1[i], // expected original behavior
};
results.push(result);
}
}
You are looking for:
let str = this['family'+id];
But this is generally a bad design pattern. Don't name your variables with incremental numbers. Use 2D arrays (i.e. arrays having arrays as values), like this.dog[id][i]. If you have "a javascript heap problem", then it is caused by some other code.

Javascript Array ES6 Undefined Error

I'm having trouble solving this question (the result is always undefined) and I am not sure what I'm doing wrong... any ideas?
Write a function that takes a number and generates a list from 0 to that number.
Use the function to assign a value to the myNumberList variable so that it has the value of a list going from 0 to 5.
Assign a value to the variable secondLastItem that should be the second last item of the myNumberList array.
function listMaker(listLength) {}
var myNumberList = null; // replace with number list created by listmaker
var secondLastItem = null; // replace with second last item
You can try the following way using ES6's spread operator (...):
function listMaker(listLength) {
return [...Array(listLength).keys()];
}
var myNumberList = listMaker(10);
// If you want the specified number passed as argument to be included as the last item in the array then push it.
myNumberList.push(10);
console.log(myNumberList);
Here is one way to write it:
function listMaker(number) {
var secondToLast;
var list = [];
for (var i = 0; i <= number; i++){
list.push(i);
}
secondToLast = list[list.length - 2];
return [list, secondToLast]
}
var list = listMaker(5)[0];
var secondToLast = listMaker(5)[1]
console.log(list + "\n" + secondToLast);
That is the snippet ^
Here is the jsfiddle

How to split a URL string with parameters into an array using JavaScript

I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.

Categories