Nested Array in JavaScript - 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

Related

Creating new array from unique elements found in array

I was given an assignment:
Finding unique elements in an array and creating a new array from these unique elements.
The professor gave us the pseudocode to code this assignment - it should be straightforward but my code is not working.
Here is my attempt:
// search for unique birthdays in the array
function find(birthdays) {
var uniqueBirthdays = [];
for (var i = 1; i <= birthdays.length; i = i + 2) {
var count = 0;
for (var j = 1; j <= birthdays.length; j = j + 2) {
if (birthdays[i] == birthdays[j]) {
count++;
}
}
if (count == 1) {
var n = uniqueBirthdays.length;
uniqueBirthdays[n] = birthdays[i - 1];
}
}
return uniqueBirthdays;
}
I have tried checking for indentation errors as well as a number of other things but can not figure out why as the array is traversed it is giving each element a count of only 1 (meaning there are no matching elements) - it does not seem to be traversing the array more than once so no elements have a count greater than 1 - even though I am using nested for loops.
I have increased the intervals by 2 because I need to compare every other element - there is a number assigned to each birthday so the array may look like:
['0001'][12/15]['0002'[03/12]...
I am brand new so I may be overlooking simple but ive tried so many things and i can not understand why this code isnt working - it is returning back all of the elements that are assigned to the birthdays instead of just the unique ones.
Any help that will point me in the right direction is very much appreciated.
You were very close, and there were just a couple mistakes. The only things that did not work were the way you wrote your for loops:
for (var i = 1; i <= birthdays.length; i = i + 2) {
Array indexes start at 0, so if you want to process the first element, use var i = 0;
Since these indexes start at 0, for an Array of 3 elements, the last index is 2. So you only want to run your loop while i is less than the array length: i < birthdays.length
You were skipping elements by doing i = i + 2. There seems to be no reason for it?
Something else worth mentionning: in JS, indentation does not matter - well, it does, but only to avoid making your eyes bleed. In fact, most websites use minified versions of their code, which fits on a single (often very long and ugly) line (example).
Here is your code, with only two lines fixed:
function find(birthdays) {
var uniqueBirthdays = [];
for (var i = 0; i < birthdays.length; i = i + 1) { // <-----
var count = 0;
for (var j = 0; j < birthdays.length; j = j + 1) { // <-----
if (birthdays[i] == birthdays[j]) {
count++;
}
}
if (count == 1) {
var n = uniqueBirthdays.length;
uniqueBirthdays[n] = birthdays[i];
}
}
return uniqueBirthdays;
}
// I used letters instead of birthdays for easier demo checking
var birthdays = ['a', 'b', 'a', 'c'];
console.log( find(birthdays) ); // ["b", "c"]
JS have direct methods tor that use Array.indexOf(), Array.lastIndexOf() and Array.filter()
uniques elements have same first position and last position
sample code:
const initailArray = [...'ldfkjlqklnmbnmykdshgmkudqjshmjfhmsdjhmjh']
const uniqueLetters = initailArray.filter((c,i,a)=>a.indexOf(c)===a.lastIndexOf(c)).sort()
console.log(JSON.stringify(uniqueLetters))

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

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.

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;
};

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.

find sequence of numbers in array and alert highest number

I have an array that looks like this:
[1,2,3,4,5,6,8,10,12,13,14,15,20,21,22,23,24,25,26,27,28,29,30]
the highest count on one of the found sequences would be: 10
My goal is to loop through the array and identify the sequences of numbers, then find the length of the highest sequence that exists.
So, based on the array above, the length of the longest sequence would be "10"
Does anyone know of quick and easy script to find this?
OK, I think I found a very short way of doing this (only 1 line for the for loop):
var arr = [1,2,3,4,5,6,8,10,12,13,14,15,20,21,22,23,24,25,26,27,28,29,30];
var res = new Array();
res[0] = 0;
for(var i=1;i<arr.length;i++) res[i] = (arr[i] == arr[i-1] + 1) ? (res[i-1] + 1) : 0;
var maxLength = Math.max.apply({},res);
this gives you (10) as the result. if you need (11) (which makes more sense) change the 0 to 1 in the for loop.
jsFiddle link: http://jsfiddle.net/gEzzA/8/
You don't need jQuery for this.
function longestSeq(arr) {
var len = 0, longestLen = -1, prev = null;
for (var i = 0; i < arr.length; ++i) {
if (prev == null || arr[i] - 1 === prev)
++len;
else {
if (len > longestLen) longestLen = len;
len = 1;
}
}
return longestLen > len ? longestLen : len;
}
What that does is keep track of how long it's been since a "break" has been seen. Each time a break is seen, it checks whether the longest so far is shorter than the last good run.
Here's the solution in pseudo code...
First, setup another array with the same number of elements and initialised to zero, to use as counters...
Array01:=[1,2,3,4,5,6,8,10,12,13,14,15,20,21,22,23,24,25,26,27,28,29,30]
Array02:=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Now the logic for filling in the counters...
FOR i:=0 TO LastElement DO
WHILE (Array01[i+1]-Array01[i]=1) AND (i<LastElement) DO Inc(Array02[i]);
Now to scan who's got the highest sequence score...
which:=0; Value:=Array02[0];
FOR i:=0 TO LastElement DO
IF Array02[i]>Value THEN BEGIN Value:=Array02[i]; Which:=i; END;
So, at the end of this the highest sequence is held by Array element "Which" and the count is "Value"!

Categories

Resources