How to iterate over a JSON object in chunks of 3? - javascript

So i have a json object that is being served by nodejs.
I'm wanting to make articles in rows of 3, then div's in rows of 3 below the articles (that contain the information for the articles.
for (var infoset in jsonObj){
createArtRow(jsonObj[infoset][info]);
createDivRow(jsonObj[infoset][info]);
// creates an article, then a div one at a time
}
I'm having issues, because i'm unsure how to join the for loop iterating over the object (only 3 at a time).
for (var infoset in jsonObj){
for (var i = 0; i < 3; i ++) {
createArtRow(jsonObj[infoset][info]);
}
for (var i = 0; i < 3; i ++){
createDivRow(jsonObj[infoset][info]);
}
}
// ideally creates 3 articles, then 3 divs at a time.
I hope that makes sense.

Use a loop that increments by 3 instead of 1.
for (var i = 0; i < jsonObj.length; i += 3) {
// here you can use jsonObj[i], jsonObj[i+1], and jsonObj[i+2] to create a row
}

You could use modulus funcion, which i think is a cleaner more readable approach:
let i =0
for (var infoset in jsonObj){
If (i % 3 == 0 ){
createArtRow(jsonObj[infoset][info]);
}
createDivRow(jsonObj[infoset][info]);
i++;
}
Modulus (%) function works by deviding 'i' by the number after the % sign.
If the remainder is 0 (so exactly dividable by 3), it will be true and execute the code.

Related

Algorithm: Next Greater Element I (from leetcode)

can someone please tell me what I'm missing in solving this algorithm? One problem I have is that my first if statement inside the nested loop is not evaluating, but I don't know why it wouldn't evaluate.
Here is the description of the problem:
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
For number 1 in the first array, the next greater number for it in the second array is 3.
For number 2 in the first array, there is no next greater number for it in the second array, so output -1.
link to original description
And here is my code so far:
var nums1 = [4,1,2];
var nums2 = [1,3,4,2];
var nextGreaterElement = function(findNums, nums) {
var holder = [];
for (var i = 0; i < findNums.length; i++) {
//loop through the 2nd array starting at the index of the first loop's current item.
for (var j = nums.indexOf(findNums[i]); i < nums.length - j; i++) {
if (nums[j+1] > nums[j]) {
holder.push(nums[j+1]);
break;
}
if (nums[nums.length]) {
holder.push(-1);
}
}
}
return holder;
};
nextGreaterElement(nums1, nums2)
Thanks for any help.
Problem: Updating variant i, but not variant j in inner loop (j-loop)
Missing: Debugging Effort
Problem Description
Theoretically, your code design should compare each value in nums1 to related parts of nums2. So, it would turn to a outer for-loop to loop on nums1 and an inner for-loop to loop related parts of nums2 for each iteration of the outer for-loop.
In your code, variant i is the index pointer for findNums (i.e. nums1) while variant j is the index pointer for nums (i.e. nums2). Variant i is always updating in both inner for-loop and outer for-loop while variant j is set once for every iteration of outer for-loop. This contradict to what you are suppose to do.
Debugging (Your Missing Work)
Find a piece of paper and a pen. Sit down, dry run the program and keep recording related info (variant i, variant j, findNums[i], nums[j], ...), you could figure out why your code is not working.
Possible Solution
var nextGreaterElement = function(findNums, nums) {
var holder = [];
for (var i = 0; i < findNums.length; i++) {
var hasNextGreaterElement = false;
// try to serach for next greater element
for (var j = nums.indexOf(findNums[i])+1; j < nums.length; j++) {
// handle case for next greater element is found
if (nums[j] > findNums[i]) {
holder.push(nums[j]);
hasNextGreaterElement = true;
break;
}
}
// handle case for next greater element is not found
if (!hasNextGreaterElement) {
holder.push(-1);
}
}
return holder;
};
var findNums=[4,1,2];
var nums=[1,3,4,2];
console.log(nextGreaterElement(findNums, nums));
You need to sort the array you are looking in to make it easier to find the number. If the array get big you might want a search algorithm to find the index in the array faster. With the array that is going to be looked in sorted you can grab the next number as the number that is one larger and check to see if you are at the end of the array. If you don't do this check the function will error when you can't find the number or when there is no number larger. Finally your second if statement didn't make sense. So I am checking to make sure that we are at the end of the array before outputting the -1 in the array.
var nextGreaterElement = function(findNums, nums) {
var holder = [];
//Should sort the array to make sure you get the next largest number
nums = nums.sort();
for (var i = 0; i < findNums.length; i++) {
//loop through the 2nd array starting at the index of the first loop's current item.
//for (var j = nums.indexOf(findNums[i]); i < nums.length - j; i++) {
for(var j = 0; j < nums.length; j++){
//check for value in array and make sure the value is not at the end
if (findNums[i] == nums[j] && j != nums.length - 1) {
holder.push(nums[j+1]);
break;
}
//check for the last element in array if so output -1
if (j == nums.length - 1) {
holder.push(-1);
}
}
}
return holder;
};

Nested Array in JavaScript

I have an array soter and a counter array. I want to get the the number of name which the count array will provide me. Is it correct ? I am a bit confused about the output. Can someone enligten me on this nested array loop in JavaScript ?
var soter = ['bp','mf','cc'],
count = [0,0,0];
for(var y = 0 ; y < soter.length; y++) {
for(var i = 0 ;i < data.SO_Ter.length; i++) {
if(data.SO_Ter[i].name == soter[y]) {
count[y]++;
That code seems correct to me, supposing the well formed object data and child SO_Ter .
So you go through the outer loop, positions 0 to 2, and for each one of them you will check that each of the items in data.SO_Ter is equal to the soter value.
If you find that value, you increment the count in 1.
Does it make sense?
To make it easier, it would be like:
for(var i = 0 ;i < data.SO_Ter.length; i++) {
if(data.SO_Ter[i].name == soter[0]) {
count[0]++;
for(var i = 0 ;i < data.SO_Ter.length; i++) {
if(data.SO_Ter[i].name == soter[1]) {
count[1]++;
for(var i = 0 ;i < data.SO_Ter.length; i++) {
if(data.SO_Ter[i].name == soter[2]) {
count[2]++;
So since you do it 3 times, you just replace those with an outer for loop.
UPDATE
count[0] represents how many times the word 'bp' has been found
count[1] represents how many times the word 'mf' has been found
count[2] represents how many times the word 'cc' has been found

Is this the right way to iterate through an array?

Here is the code in question:
var L1 = [];
var Q1 = [];
function populateListOne() {
var limit = prompt("please enter a number you would like to fill L1 to.");
for (i = 2; i <= limit; i++) {
L1[i] = i;
}
for (n = 2; n <= L1.length; n++) {
var count = 2;
if (n == count) {
var index = L1.indexOf(n);
L1.splice(index, 1);
Q1[n] = n;
count = count + 1;
}
for (j = 0; j <= L1.length; j++) {
if (L1[j] % 2 == 0) {
var secondIndex = L1.indexOf(j);
L1.splice(secondIndex, 1);
}
}
}
document.getElementById("demo").innerHTML = "iteration " + "1" + ": " + L1 + " Q1 = " + Q1;
}
I’m currently working on a homework assignment where I have to setup a queue. All is explained in my JSFiddle.
Problem description
Essentially, the part I’m stuck on is iterating through each instance of the array and then taking the value out if the modulus is identical to 0. However, as you can see when I run the program, it doesn’t work out that way. I know the problem is in the second for loop I just don’t see what I’m doing wrong.
The way I read it is, if j is less than the length of the array, increment. Then, if the value of the index of L1[j] modulus 2 is identical to 0, set the value of secondIndex to whatever the index of j is. Then splice it out. So, theoretically, only numbers divisible by two should be removed.
Input
A single number limit, which will be used to fill array L1.
L1 will be initialized with values 2, 3, ... limit.
Process
Get the starting element of array L1 and place it in array Q1.
Using that element, remove all values in array L1 that are divisible by that number.
Repeat until array L1 is empty.
You're going to have issues with looping over an array if you're changing the array within the loop. To help with this, I tend to iterate from back to front (also note: iterate from array.length - 1 as the length element does not exist, arrays are key'd from 0):
for(j = L1.length - 1; j >=0 ; j--)
For your first loop, you miss the elements L1[0] and L1[1], so I would change the first loop to:
L1 = [];
for(i = 2; i <= limit; i++)
{
L1.push(i);
}
In this section:
for(j = 0; j <= L1.length; j++){
if(L1[j] % 2 == 0)
{
var secondIndex = L1.indexOf(j);
L1.splice(secondIndex, 1);
}
}
you should splice with j instead of secondIndex.
Change L1.splice(secondIndex, 1); to L1.splice(j, 1);
Array indices and putting entries
You initial code used an array that was initialized to start at index 2. To avoid confusion, of what index to start at, start with index 0 and iterate until array.length instead of a predefined value limit to ensure that you go through each element.
The following still works but will be more of a headache because you need remember where to start and when you will end.
for (i = 2; i <= limit; i++) {
L1[i] = i; // 'i' will begin at two!
}
Here's a better way:
for (i = 2; i <= limit; i++) {
// 'i' starts at 2 and since L1 is an empty array,
// pushing elements into it will start index at 0!
L1.push(i);
}
Use pop and slice when getting values
When you need to take a peek at what value is at the start of your array, you can do so by using L1[0] if you followed my advice above regarding array keys.
However, when you are sure about needing to remove the starting element of the array, use Array.slice(idx, amt). idx specifies which index to start at, and amt specifies how many elements to remove beginning at that index (inclusive).
// Go to 1st element in L1. Remove (1 element at index 0) from L1.
var current = L1.splice(0, 1);
Use the appropriate loops
To make your life easier, use the appropriate loops when necessary. For loops are used when you know exactly how many times you will iterate. Use while loops when you are expecting an event.
In your case, 'repeat until L1 is empty' directly translates to:
do {
// divisibility checking
} while (L1.length > 0);
JSFiddle
Here's a complete JS fiddle with in-line comments that does exactly what you said.

Two loops performance difference. Swapping inner and outer loop

I had two loops (one nested in the other one) and I was wondering if there is any difference in how I nest these loops. Results of Code 1 and Code 2 are the same (100,000x4 = 4x100,000 = 400,000) but jsPerf shows that Code 2 is roughly 50% faster than Code 1.
I'd like to kindly ask for your advice, I don't understand the difference between the two.
Thank you very much.
var tt = function () {
// do some stuff
// for example:
return (3);
};
Test code 1:
for (var i = 0; i < 100000; i++) {
for (var j = 0; j < 4; j++) {
tt();
}
}
Test code 2:
for (var j = 0; j < 4; j++) {
for (var i = 0; i < 100000; i++) {
tt();
}
}
The difference is in the loop initialization code. The first code has to initialize the inner loop 100,000 times while the second one only does that 4 times.
Analyze the code as if each operation had a cost and you will see that this makes sense.
In test code 2, you are stuck on the nested loop 100,000 times, but go to the outer loop 4 times.
Instead, in test code 1, you alternate between the two.
The first test code runs more operations than the seconds.

I'm having difficulty populating a two dimensional array with random Boolean values and then reading those values back out in JavaScript

I'm working on a really simple cellular automata program in JavaScript. For right now I just want to write a bunch of random Boolean values to a two-dimensional array and then read that array back to be manipulated or displayed in some way.
var dimension = 5;
var grid = new Array();
for (x = 0; x < dimension; x++) {
grid[x] = new Array();
}
//populate grid
for (i = 0; i < dimension; i++) {
document.write('<br>');
for (j = 0; j < dimension; j++) {
grid[i,j] = Math.floor(Math.random()*2);
document.write(grid[i,j]);
}
}
for (i = 0; i < dimension; i++) {
document.write('<br>');
for (j = 0; j < dimension; j++) {
document.write(grid[i,j]);
}
}
So, I've whittled the code down to a few nested for loops where I cycle through and populate the array and then print it back. Note that the output generated during the population loop is what I want, random values. But when I read the array back, it seems like the last row (I think it's really a column, but it's displayed horizontally) has been copied to all the others...
I've done this sort of thing before in other languages and never had a problem like this.
I'm new to this community and JavaScript in general so this might be a dumb questing or I may not have presented it helpfully. I would really appreciate any help or advice on how I can improve my question.
Array indexes in JavaScript are not comma seperated. You need to use brackets. So for your two dimensional array it will be:
grid[i][j]; // not grid[i,j]

Categories

Resources