Order of execution in loop - javascript

I'm using this function to get some infos from google analytics and trying to stick them in a JS object in order to send it to the user.
My problem is: the console.log(obj) gets executed before the obj.push(tempObj);. So when I try to send the obj, I find it empty.
I tried to use async.each() & async.waterfall() but still had the same problem.
function getJsonFileByUser2() {
authClient.authorize((err, tokens) => {
let dimensions, webproperties;
let accounts = getAccountsByUser();
let obj = [];
for (var i = 0; i < accounts.length; i++) {
let tempObj = {
account_id: accounts[i]["id"],
account_name: accounts[i]["name"],
webproperties: []
};
webproperties = getWebPropertyIdByAccount(accounts[i]["id"]);
for (let j = 0; j < webproperties.length; j++) {
dimensions = getDimensions(accounts[i]["id"], webproperties[j]["id"]);
tempObj.webproperties.push({
id: webproperties[j]["id"],
name: webproperties[j]["name"],
dimensions: dimensions
});
}
obj.push(tempObj);
}
console.log(obj);
});
}

Related

How to create an array of objects , where all properties are fixed, values are generated randomly and it's get fixed after generated once?

I am learning react as beginner , I am trying to create an array of products object. I have created it in a js file. Then exported the array. In another file I have imported and it works. Problem is whenever I refresh the page it gets new random values. As I have use random function to generate the object values. What I want is, after generating the array of objects once, it won't generate randomly further. How can I do that?
export const cosmetics = [];
const names = [];
const prices = [];
//random generated name list---------------------------------
function set_name() {
const letters = 'abcdefghijklmnopqrstuvwxyz'
for (let j = 0; j < 20; j++) {
let name = '';
for (let i = 0; i < 4; i++) {
name += letters.charAt(Math.floor(Math.random() * 26))
}
names.push(name)
}
}
// random generate prices list ---------------------------
function set_price() {
for (let j = 0; j < 20; j++) {
prices.push(Math.floor(Math.random() * 500) + 1000)
}
}
// create data set array of objects
function construct_data() {
for (let i = 0; i < 20; i++) {
const cosmetic = {
id: i + 1,
name: names[i],
price: prices[i]
}
cosmetics.push(cosmetic)
}
}
set_name();
set_price();
construct_data();

I am stuck at a JavaScript function that should count all unique items in an array

I wanted to create a function, that counts all unique Items in an array, but somehow I do not get any output.
This is my array!
let arr = ["hi", "hello", "hi"];
And this is the code I wrote so far:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
countUnique(arr);
}
console.log(countUnique(arr));
Your are counting values correctly, however then you are calling this method recursively countUnique(arr); and it results an error of call stack exceeded.
So just remove recursive call of method countUnique(arr); and return counted value counts:
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
counts[arr[i]] = 1 + (counts[arr[i]] || 0);
}
return counts;
}
let arr = ["hi", "hello", "hi"];
console.log(countUnique(arr));
JavaScript engine limits the maximal recursion depth. We can rely on it being 10000, some engines allow more.
You could take a Set and return the size.
const countUnique = array => new Set(array).size;
console.log(countUnique(["hi", "hello", "hi"]));
let arr = ["hi", "hello", "hi"];
function countUnique(arr) {
var counts = {};
for (var i = 0; i < arr.length; i++) {
if(arr[i] in counts) {
counts[arr[i]]++;
} else {
counts[arr[i]] = 1;
}
}
return Object.keys(counts).length;
}
console.log(countUnique(arr));

Make javascript variable can be empty

Hi i have this function below that removes duplicates from the variable suggest but sometimes the data i receive for the suggest variable is empty and the code below wont work beacause of the JSON.parse function how do i make it so that the variable accepts empty data so that the code below will still run without any problems. Any help would be appreciated thanks!
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
You can set suggest inside an if condition to check whether data exists or not
function suggestData(data){
var suggest = [];
if(data){
suggest = JSON.parse(data);
}
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Also you can simply end the function if you do not want to execute it when data is empty:
function suggestData(data) {
if(!data){
return false;
}
//other code here
...
}
Set the length conditionally as,
var length = suggest? suggest.length: 0;
function suggestData(data){
var suggest = [];
suggest = JSON.parse(data);
var length = suggest? suggest.length: 0;
for (var i = length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
}
suggestData(null);
function suggestData(data){
var suggest = []; // I tried adding this and setting it to null but it doesn't seem to work.
if(data)
suggest = JSON.parse(data);
for (var i = suggest.length - 1; i >= 0; i--) {
for (var j = 0; j < arrString.length; j++) {
if (suggest[i] === arrString[j]) {
suggest.splice(i, 1);
}
}
}
Just add the if condition on parsing line like
written in above code::
if(data)
suggest = JSON.parse(data);
The simplest:
if(!data || !suggest)
return;
let array = [1,2,3,8,3,4,4,5]
const removeDuplicateItems = arr => [...new Set(arr)];
console.log(removeDuplicateItems(array))
If you just want to remove duplicated items in an array, you can instead try Set which is quite handy
Even if array is empty or null, this method removeDuplicateItems will still works

Javascript/Node - Insertion of objects into array using for loop

I need help regarding insertion of array elements as objects into another array in Javascript. I have the following code:
tableLength = 3;
nyCourt = [];
oldArr = [Buy, String, Question]
for (var t = 0; t < tableLength; t++) {
nyCourt.push({});
for (var i = 0; i < OldArr.length; i++) {
nyCourt.Title = OldArr[i] ;
}
};
The code isnt working, I want output in the following format
[{Title:Buy },
{Title: String},
{Title: Question}]
But the output I get is this:
[{Title:Question },
{Title: Question},
{Title: Question}]
This line:
nyCourt.Title = OldArr[i]
writes to the Title property on the nyCourt object (which is an array object), repeatedly in the loop. The last assignment wins.
But given what you've said you want your output to be, your code is over-complex. You only need one loop:
var nyCourt = [];
var oldArr = [Buy, String, Question];
for (var i = 0; i < oldArr.length; i++) {
nyCourt.push({Title: oldArr[i] });
}
Live Example (use Chrome or something else modern) | Source
Or as this is Node so we know we have map:
var oldArr = [Buy, String, Question];
var nyCourt = oldArr.map(function(entry) {
return {Title: entry};
});
Live Example | Source
//this give the output you want
tableLength = 3;
nyCourt = [];
oldArr = ['Buy', 'String', 'Question'];
for (var t = 0; t < oldArr.length; t++) {
nyCourt.push({Title: oldArr[t]});
};
console.log(nyCourt);
place that push function inside the loop also change the code like this
for (var t = 0; t < tableLength; t++) {
for (var i = 0; i < OldArr.length; i++) {
nyCourt.push({"Title": oldArr[t]});
}
};

Regrouping javascript array

I have the below javascript array with me
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15}
},
{
Science:{
ST1:50,
ST3:40}
}
]
I want to generate the array shown below out of this
var t = [{ST1:{
Maths:10,
Science:50
},
ST2:{
Maths:2,
Science:0
},
ST3:{
Maths:15,
Science:40
}
}]
I tried using the code shown below
for (var key in test) {
if (test.hasOwnProperty(key)) {
for (var key1 in test[key]){
//console.log(key1)}
var abc = test[key][key1];
for(var x in abc)
{
console.log(x+key1+abc[x])
}
}
}
}
I am new to this help me doing this.
This does mostly what you want...
var t = {};
for (var i = 0; i < test.length; i++) {
for (var name in test[i]) {
for (var level in test[i][name]) {
if (!t[level])
t[level] = {}
t[level][name] = test[i][name][level]
}
}
}
Only thing missing is to get the Science:0 for when a STx value is missing under a section.
DEMO: http://jsfiddle.net/eHwBC/
Result:
{
"ST1": {
"Maths": 10,
"Science": 50
},
"ST2": {
"Maths": 2
},
"ST3": {
"Maths": 15,
"Science": 40
}
}
Keep in mind that there's no guaranteed order when using for-in for enumeration.
If the labels (Math, Science, etc) are known in advance, then you can ensure that each object gets all labels.
If not, a separate loop can be done. Depending on the approach, it could be done before or after this main loop.
Do you know about JSON.stringify(t)?
It will convert an object literal to JSON.
Mozilla's documentation of this function is available at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.
You can also read this blog article for further explanation
Try this:
var test =[{
Maths:{
ST1:10,
ST2:2,
ST3:15
}
},
{
Science:{
ST1:50,
ST3:40}
}
];
var result = [];
for(i = 0; i <= test.length; i++){
var resultRow = {};
for(key in test[i]){
for(subKey in test[i][key]){
if(resultRow[subKey] == undefined){
resultRow[subKey] = {};
}
resultRow[subKey][key] = test[i][key][subKey];
}
}
result.push(resultRow);
}
Try like below,
/* Iterator start */
var t = {};
for (var i = 0; i < test.length; i++) { //Iterate Maths, Science,..
for (var key in test[i]) { //Iterate Math
for (var iKey in test[i][key]) { //Iterate ST1, ST2, ST3
var s = (t.hasOwnProperty(iKey))?t[iKey]:createObject();
s[key] = test[i][key][iKey];
t[iKey] = s;
}
}
}
/* Iterator End */
p = [];
p.push(t);
//^- p is what you want
// Separate function so you can add more items later without changing logic
function createObject () {
return {'Maths' : 0, 'Science': 0};
}
DEMO and Proof below,

Categories