I am currently trying to loop and add each element of the quantity of each bid and ask which appears as bids[0][1], bids[1][1], bids[1][2] and add each element in the Array sequence. Any help will be greatly appreciated.
I tried adding the array but I am unable to turn the Json data to code here. Below is the API reference
I tried the code:
const binanceTrade = JSON.parse(data)
const bidsQuantity = binanceTrade.bids[0][1]
const askQuantity = binanceTrade.asks[0][1]
for(var i = 0; i<bidsQuantity.length; i++){
var j = 1;
bidsQuantity = bidsQuantity.push(binanceTrade.bids[j][1])
console.log(bidsQuantity)
j++
//bids[0][1] + bids[1][2]
}
And the public Binance API route for reference: https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=5
You can use reduce() to loop over the bids and asks arrays, totaling the second element of each item.
const binanceTrade = JSON.parse(data);
const bidsQuantity = binanceTrade.bids.reduce((acc, [_, quantity]) => acc + quantity, 0);
const asksQuantity = binanceTrade.asks.reduce((acc, [_, quantity]) => acc + quantity, 0);
One approach would be to use map
const bidsQuantity = [];
binanceTrade.bids.map((bids) => {
bidsQuantity.push(bids[1]);
});
You can do this again in a similar way for the asks
Related
Having a hard time understanding for loops in arrays. Trying to create a Thank You card creator and these are the steps I'm trying to follow:
Create a new, empty array to hold the messages
Iterate through the input array and inside the loop build out the 'thank you' message for each name using string interpolation, then add that message to the new array you created
After the loop finishes and all of the messages have been added to the new array, return the new array.
const names = []
function writeCards(names, event) {
for (let i = 0; i < names.length; i++) {
console.log(`Thank you, ${names[i]} for the wonderful ${event} gift!`);
return names;
}
Not sure if I'm on the right track. Thanks for your help!
I know your question is focused on for loop, but just in case, you might be interested in using map to achieve the desired result in a more concise manner:
const names = ["Joe", "Nina"]
function writeCards(names, event) {
return names.map(name=> `Thank you, ${name} for the wonderful ${event} gift!`)
}
console.log(writeCards(names, "birthday"))
You can use Array.push()
function writeCards(names, event) {
let messages = []
for (let i = 0; i < names.length - 1; i++) {
messages.push("Thank you, " + names[i] + " for the wonderful " + event + " gift!")
}
return messages;
}
well the i had this issue
i had an empty array outside a loop and wanted to update it inside a loop
and finally return an array with alot of indexes
//ie
//let arr = []
//LOOP then runs
//then console.log(arr) //console shows [1,2,3,4,5,6,7]
this is how you do it
let arr = []
let realArray = [1,2,3,4,5]
for (let index = 0; index < realArray.length; index++) {
const element = realArray[index]
arr.push(element)
}
console.log(arr)//your arr = 1,2,3,4,5
this is my first answer here
function writeCards(names, event) {
// 1) Create a new, empty array to hold the messages.
// So, this should be done within the function. We want to be
// able to update this locally-scoped array with the information
// we get from each name in the array, combined with the event
const messages = [];
for (let i = 0; i < names.length; i++) {
// 2) using string interpolation
// What's great is that you've already discovered template strings
// String concatenation has its uses but this far better.
const message = `Thank you, ${names[i]}, for the wonderful ${event} gift!`;
// So, instead of logging the message to the console
// we're going to push it to the messages array
messages.push(message);
}
// 3) After the loop finishes and all of the messages
// have been added to the new array, return the new array.
return messages;
}
console.log(writeCards(['Bob', 'Sue'], 'wedding'));
I would rather suggest to go with #DoneDeal0 answer's.
In case, if you would like to go with for loop, there's one more cleaner way to go with it. You can use forEach() function given by javascript, as it takes two parameters in it, first is the value of each index and second is the index number itself.
Note: forEach() is just similar to for(i=0; i<n; i++).
names = ["Robert", "King", "Joey"];
function writeCards(names) {
let messages = [];
names.forEach((name, index) => {
messages.push("Thank you, " + name + " at " + index + " for the wonderful gift");
});
return messages;
}
console.log(writeCards(names));
I am practicing blog stuff. posting and deleting posts. mini social media I can say. And I wanted to save posts on localStorge. however I could save only 1 post at a time. and then I wanted to do it with IDs.
I create id with random number generator:
let newId = Math.floor(Math.random() * (1000000 - 100000) + 100000)
let postContents = {
ID : newId,
text: value,
}
an then I upload those values in let storedPosts = [] array.
then I save it to local storage with JSON:
let toJson = () => {
localStorage.setItem('storedPosts', JSON.stringify(storedPosts));
}
and then I get it from Local Storage:
let storedJsonPosts = localStorage.getItem('storedPosts')
let storedPosts_toUpload = JSON.parse(storedJsonPosts)
and then I join these two arrays together:
let storedPostsArray = storedPosts.concat(storedPosts_toUpload)
and after this I don't know what to do. I tried this:
let uploadStoredPosts = () => {
for (let i = 0; i < storedPostsArray.length; i++) {
let post = document.createElement('div')
$post_place.appendChild(post)
let text = document.createElement('p')
post.appendChild(text)
text.textContent = storedPostsArray[i].text
}
}
but it showed this:
It couldn't reach array values. plz help
Is this something that you're after?
The code reads from localStorage, parses that information, returns an empty array if it's the first time the user posted, pushes a new value to the array, stores that array by stringifying it, and the appending the new value to the document.
If you want the page to read from localStorage on page load, you need to add a function that reads from localStorage, and then loops through all posts to add each one of them by using appendToDocument().
StackOverflow doesn't allow the use of localStorage, so I used a variable for demo purposes.
I left out id as a property. You can play around with that by yourself, but I would suggest to use a timestamp as a foreign key ("id").
var justForDemoPurpose = null;
const addPostBtn = document.getElementById("add-button");
const addPostInput = document.getElementById("add-post");
const postContainerEl = document.getElementById("post-container");
addPostBtn.addEventListener('click', addPost);
function readFromLocalStorage(key) {
let localStorageItem = JSON.parse(justForDemoPurpose);
// let localStorageItem = JSON.parse(localStorage.getItem(key));
console.log('returning items:', localStorageItem);
return localStorageItem;
}
function storeInLocalStorage(key, value) {
justForDemoPurpose = JSON.stringify(value);
// JSON.stringify(localStorage.setItem(key, value));
}
function addPost() {
let postValue = addPostInput.value;
if (postValue) {
const LOCAL_STORAGE_KEY = 'posts';
let storedPosts = readFromLocalStorage(LOCAL_STORAGE_KEY) || [];
storedPosts.push(postValue);
storeInLocalStorage(LOCAL_STORAGE_KEY, storedPosts);
appendToDocument(postValue);
}
}
function appendToDocument(postValue) {
let divEl = document.createElement('div')
divEl.textContent = postValue;
postContainerEl.appendChild(divEl);
}
<div class="addPostContainer">
<input id="add-post" placeholder="Type here"> <button id="add-button">Add Post</button>
</div>
<section id="post-container"></section>
I am trying to post all entries in a 1d array to a column in a google sheets. The array is the product of filtering two larger arrays and returning the names that do not appear on both lists.
below is an example of the generated array.
unPub = [fake name, test1, test2, test3]
Here is the code I have written so far:
function unPublished(){
const q3 = SpreadsheetApp.openById("1111111111");
const packAllergies = q3.getSheetByName("PACK_ALLERGIES");
const packSrch = packAllergies.getRange("D5:D" + packAllergies.getLastRow()).getValues().flat();
const allergyNames = allergy.getRange("A2:A" + allergy.getLastRow()).getValues().flat();
var unPub = (packSrch.filter(e => !allergyNames.includes(e)));
var sRow = allergy.getLastRow()+1
if (unPub.length > 0){
unPub.forEach(e => allergy.getRange(sRow,1).setValue(e));
}
}
I have tried a for loop to iterate over the list as well as forEach and still only get the last entry of the unPub array to post in the defined range.
How can I get each element in the array to post to the column starting at sRow?
Explanation:
You don't need a loop to set values to the sheet. In fact it is not recommended, see best practices.
You need the following two steps:
transform your row array into a column array:
unPub=unPub.map(v=>[v]);
because you want to set the data into a column.
remove the forEach loop and directly pass the values with a single line:
allergy.getRange(sRow,1,unPub.length,1).setValues(unPub);
Solution:
function unPublished(){
const q3 = SpreadsheetApp.openById("1111111111");
const packAllergies = q3.getSheetByName("PACK_ALLERGIES");
const packSrch = packAllergies.getRange("D5:D" + packAllergies.getLastRow()).getValues().flat();
const allergyNames = allergy.getRange("A2:A" + allergy.getLastRow()).getValues().flat();
var unPub = (packSrch.filter(e => !allergyNames.includes(e)));
var sRow = allergy.getLastRow()+1;
unPub=unPub.map(v=>[v]);
allergy.getRange(sRow,1,unPub.length,1).setValues(unPub);
}
Issue with your approach:
Besides performance issues which I described in the explanation section, your forEach loop does not work because you overwrite every value on the same cell. If you see, this part allergy.getRange(sRow,1) does not change in the for loop, given that sRow is constant.
If you want your approach to work, then you need to introduce an iterator i in the forEach loop and use that to iterate through the cells:
unPub.forEach((e,i) => allergy.getRange(sRow+i,1).setValue(e));
function unPublished(){
const q3 = SpreadsheetApp.openById("1111111111");
const packAllergies = q3.getSheetByName("PACK_ALLERGIES");
const packSrch = packAllergies.getRange("D5:D" + packAllergies.getLastRow()).getValues().flat();
const allergyNames = allergy.getRange("A2:A" + allergy.getLastRow()).getValues().flat();
var unPub = (packSrch.filter(e => !allergyNames.includes(e)));
var sRow = allergy.getLastRow()+1
if (unPub.length > 0){
unPub.forEach((e,i) => allergy.getRange(sRow+i,1).setValue(e));
}
}
but I really recommend you the first approach I mentioned.
This is my code
categories = [{"id":"101","name":"category1"},{"id":"102","name":"category2"},{"id":"103","name":"category3"},{"id":"104","name":"category4"}];
actions = [{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"},{"id":"203","name":"action3","category_id":"102"},{"id":"204","name":"action4","category_id":"104"}];
In the above categories array id value is existed in actions array. so i want to combine the two arrays into one array like the output as follows.
Output:-
finalList = [{"id":"101","name":"category1","actions":[{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"}]},{"id":"102","name":"category2","actions":[{"id":"203","name":"action3","category_id":"102"}]},{"id":"103","name":"category3","actions":[]},{"id":"104","name":"category4","actions":[{"id":"204","name":"action4","category_id":"104"}]}]
for each category find action elements and add then to category object
this.categories.forEach((element) => {
element['actions'] = this.actions.filter((data) => data.category_id === element.id);
});
console.log(this.categories);
use the map function along with the filter
var categories = [{"id":"101","name":"category1"},{"id":"102","name":"category2"},{"id":"103","name":"category3"},{"id":"104","name":"category4"}];
var actions = [{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"},{"id":"203","name":"action3","category_id":"102"},{"id":"204","name":"action4","category_id":"104"}];
var result = categories.map((item) => {
item.action = actions.filter( ac => item.id === ac. category_id)
return item;
})
console.log(result)
You can simply use Array.reduce() to create a map of actions ,group by category Id. And than you can use Array.map() on the categories to get the desired result. The overall time complexity of this solution will be O(n).
let categories = [{"id":"101","name":"category1"},{"id":"102","name":"category2"},{"id":"103","name":"category3"},{"id":"104","name":"category4"}];
let actions = [{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"},{"id":"203","name":"action3","category_id":"102"},{"id":"204","name":"action4","category_id":"104"}];
let map = actions.reduce((a,curr)=>{
(a[curr.category_id] = a[curr.category_id] || []).push(curr);
return a;
},{});
let result = categories.map((o)=>{
o.actions = map[o.id] || [];
return o;
});
console.log(result);
// Use simple for loop along with filter
categories = [{"id":"101","name":"category1"},{"id":"102","name":"category2"},{"id":"103","name":"category3"},{"id":"104","name":"category4"}];
actions = [{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"},{"id":"203","name":"action3","category_id":"102"},{"id":"204","name":"action4","category_id":"104"}];
for(var i=0;i<categories.length;i++){
categories[i]['actions'] = actions.filter((data) => data.category_id === categories[i].id);
};
console.log(categories)
I am using for loops working fine.
for(var i=0;i<categories.length;i++)
{
categories[i]["actions"]=[];
for(var j=0;j<actions.length;j++)
{
if(categories[i].id==actions[j].category_id){
categories[i]["actions"].push(actions[j]);
}
}
}
Any other approach without using for loops?
I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}