Fetching the two values from second inner array - javascript

hey guys am a javascript developer..I have a multidimensional array..
My array structure looks like
var m = [[1,23,4],[4544,34,54],[6,7,68]]
What i want to display is 4544 and 34 from a single code(not by slicing or replacing)
My code is
var m = [[1,23,4],[4544,34,54],[6,7,68]]
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
console.log(m[i][j]);
}
}
This code outputs me 1,23,4544 and 34.
The output i needed is 4544 and 34..
Thanks..

There is no need for the first for loop you have, but the second can work, even though it is not necessary. With the loop you can do
var m = [[1,23,4],[4544,34,54],[6,7,68]];
for(i=0;i<2;i++) {
console.log(m[1][i]);
}
This will just print the first two elements from the second array inside the m array. You can also do this easily without a loop like this
var m = [[1,23,4],[4544,34,54],[6,7,68]];
console.log(m[1][0]);
console.log(m[1][1]);
They are both relatively short and they both produce the result
4544
34
What is wrong with the current code you have
var m = [[1,23,4],[4544,34,54],[6,7,68]]
for(i=0;i<2;i++) {
for(j=0;j<2;j++) {
console.log(m[i][j]);
}
}
With your first loop, you are actually iterating through the first two nested arrays that you have. Then, you are looping through the first two items in each of those. This is why you get the result of
1
23
4544
34
Since you only need items in the second nested array, there is no reason to have a second loop. Of course, you could do
var m = [[1,23,4],[4544,34,54],[6,7,68]]
for(i=1;i<2;i++) {
for(j=0;j<2;j++) {
console.log(m[i][j]);
}
}
but that would be pointless.

You could keep the first index fixed and only loop on the second index
var j, i=1
for (j=0;j<2;++j) {
console.log(m[i][j])
}

var m = [[1,23,4],[4544,34,54],[6,7,68]]
for(j=0;j<2;j++) {
console.log(m[1][j]);
}

Related

Apps Script For Loop stuck at 0 in iteration although it is running

I have an array 'vnData' containing 5, 6 rows from where I am trying to extract 3rd column values (based on a criteria) and insert to a new array. Here is my code
for (odr = 0; odr < vnData.length; odr++){
Logger.log(vnData);
tempOdr = vnData[odr][3];
Logger.log(odr);
Logger.log(tempOdr);
Logger.log(vnData[odr][3]);
for(k = 0; k < vnData.length; k++){
if(vnData[k][3] = tempOdr){
odrVal = odrVal + vnData[k][11];
}
}
if(odrVal > 0){
affOdrSet.push(tempOdr);
}
Logger.log(affOdrSet);
}
Logger gives right value of odr in Logger.log(odr); but in Logger.log(vnData[odr][3]); I am always getting a result where value of odr is 0.
So for each iteration I get value from first row. Please help what is wrong in it.
One more thing, if I log Logger.log(vnData[3][3]) in place of Logger.log(vnData[odr][3]) then for first iteration it gives me right value from row 4 but for all subsequent iterations even Logger.log(vnData[3][3]) gives value from first row which is really weird.
The problem is the expression of the first if statement. Instead of
vnData[k][3] = tempOdr
use
vnData[k][3] === tempOdr
The above because = is the assign operator but it's very likely that instead of assigning tempOdr to vnData[k][3] what you want to compare them.

Sorting Elements of multidimensional Array at a certain Index

I have an Array of Arrays. My Array is
splitarr[Array0[],Array3[],Array[2],Array[1],Array[4]...]
It is not ordered correctly as you see, I want to order it so it would look something like that.
splitarr[Array0[],Array1[],Array2[],Array3[],Array[4]...]
To understand the whole thing better. There are various "functions" which determine where the array will be sorted. So far I have written a function which orders the array correctly when the "index", where it is ordered incorrectly is 0. But to fully explain how I know where it is ordered incorrectly would take too long to explain.
var dividersecond = 2;
The "divider second", derives from a function. But what is important to know in this context, is that my array is ordered incorrectly at those amount of Positions like this for example:
splitarr[Array2[],Array1[],Array0[],Array3[]...]
var splitarrayindex = 0;
This is the Index of the Array at which the incorrect order starts.
mySplitArray = ReorderArray(dividersecond,splitarrayindex,mySplitArray);
function ReorderArray(Count,Index,Array){
var originalIndex = Index;
for(Index;Index<Count-1;Index++){
var swapIndex= (Count-Index);
var temp = Array[Index];
Array[Index] = Array[swapIndex];
Array[swapIndex] = temp
}
Array.splice(originalIndex,1);
return Array;
}
This function works, as long as the index is 0. Which makes sense.
One of my problems is "Count-1", in the "for-loop". When my Index is "0", and 3 Elements (divider = 2) are ordered incorrectly, I of course need "2" Times of swapping. If my Index is "1", then "Count-1", would mess with this.
There are other things that determine wether my Array will be ordered correctly, for Example determining the Current Index and the Current Swap Index.
All of this and the fact that I am new to Javascript and sorting Arrays, leave me solutionless. If someone could help me with a function that would be awsome!
Here is a quick description of what I wanna do in my Code. (Visualized with Numbers)
2103
(swap at 0 and 2)
0123
Code like this works already because the Index is 0
03214
(Swap Index 1 and Index 3)
01234
How can I make this work?
I think this solved the Problem. Not entirely sure yet. But I will try it with other numbers and Indexes, to see wether it works.
function ReorderArray(Count,Index,Array){
var originalIndex = Index;
for(var i = 0; i<Count-1;i++){
var swapIndex = ((Count+originalIndex)-i);
var temp = Array[originalIndex+i];
Array[originalIndex+i] = Array[swapIndex];
Array[swapIndex] = temp;
}
//delete the position at the original Index
Array.splice(originalIndex,1);
return Array;
}

Include duplicates in for and if loop of array as count number is too small

I'm new to javascript so any help would be greatly appreciated.
What I'm trying to do is cycle through every element in the array and count the number of times the value of an element matches a given condition (even if the value is duplicated).
function loaddata(xml) {
var count = 0;
var i;
var xmlDoc = xml.responseXML;
var z = xmlDoc.getElementsByTagName("group");
if (value1 <= value2) {
for (i = 0; i < (0 + z.length); i++) {
if (z[i].getElementsByTagName("name")[0].childNodes[0].nodeValue == "John") {
count++;
}
}
}
$('#count1').html(count);
};
The count value outputted is too small. I believe the reason for this that the for loop isn't iterating through all elements in the array. When I remove the second if loop and output the count for just the for loop this value is also too small. I believe that the for loop isn't searching through the duplicate elements of the array (i.e. it is ignoring them so that they aren't then fed into the second if loop). Is it possible to specify that the for loop include duplicates?
Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.
Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.
Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");
I hope that helps,

Want to add a value and remove on a single click using javascript or jquery

I am using a onclick function and adding a value to by paasing a value to it. If the value already exists den i remove that value from the list.
function send_value(str)
{
//alert(str);
var sub_id = document.getElementById('selected_sub_id').value;
//alert(sub_id.indexOf(str));
if(sub_id.indexOf(str)==-1)
{
if(sub_id=="")
{
sub_id+=str;
}
else
{
sub_id+=',';
sub_id+=str;
}
}
else
{
sub_id = sub_id.replace(str+",", "");
sub_id = sub_id.replace(","+str, "");
sub_id = sub_id.replace(str, "");
}
//alert(sub_id);
document.getElementById('selected_sub_id').value=sub_id;
}
This is the function. Suppose i have the values 1,2,3,4 in the selected_sub_id and i am passing 5 to it, it will be stored as 1,2,3,4,5
now i am passing 24 it will be stored as 1,2,3,4,5,24
No suppose i want to remove 2, so when i send 2 to the function it removes all the occurrences of 2 so i am left with only 1,3,4,54...
kindly help me with this thanks in advance..
You most probably want an array for this. It makes things much easier.
Create one first:
var arr = [];
Adding goes with .push:
arr.push(24);
Removing goes with .splice and .indexOf (the 1 means 'removing 1 element'):
arr.splice(arr.indexOf(24), 1);
Converting to a string goes with .join:
arr.join(); // 1,2,3,24 or something similar depending on elements
For example: http://jsfiddle.net/ScBNQ/.
var arr = [];
// adding
arr.push(1);
arr.push(2);
arr.push(3);
arr.push(24);
// removing
arr.splice(arr.indexOf(2), 1);
// joining
arr.join(); // 1,3,24

Create multiple arrays based on frequency of coordinates in an array

Using JavaScript, I'd like to split one big array of coordinates into smaller arrays based on coinciding points. I am not 100% sure how to write the following in code but it describes what I'm attempting to achieve:
Iterate through the array
var A = [(1,2)(1,3)(2,3)(9,10)(9,11)(10,11)];
Combine the pairs that contain any matching/identical coordinate points:
var B = (1,2)(1,3)(2,3)
var C = (9,10)(9,11)(10,11)
Combine the matching/identical points and create new, smaller arrays from the combinations in point #2
var D = [1,2,3]
var E = [9,10,11]
Can I get help please?
Working answer: http://jsfiddle.net/y3h9L/
OK, so if I understand the requirement A is a one-dimensional array that is assumed to have an even number of elements in x,y pairs.
A = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11]
// output should be
[ [1,2,3], [9,10,11] ]
// but if you add an extra pair that links the two halves, say add 2,11
A2 = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11, 2,11]
// then all are related so output should be
[ [1,2,3,9,10,11] ]
I've made no effort to pretty-up or optimise the following code, but it works:
// single dimensional array of x,y pairs
var A = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11];
// create a working copy of A so that we can remove elements
// and still keep the original A intact.
var workingCopy = A.slice(0, A.length),
matchedPairs = [],
currentMatches,
finalCombinations = [],
x, y, i, j,
tempArray;
while (workingCopy.length > 0) {
currentMatches = [];
currentMatches.push([workingCopy.shift(),workingCopy.shift()]);
workingCopyLoop:
for (x=0,y=1; x < workingCopy.length;) {
for (i=0; i < currentMatches.length; i++){
if (workingCopy[x] === currentMatches[i][0]
|| workingCopy[y] === currentMatches[i][1]) {
currentMatches.push([workingCopy.shift(),workingCopy.shift()]);
// go back to the beginning of workingCopyLoop
x=0;
y=1;
continue workingCopyLoop;
}
}
x += 2;
y += 2;
}
matchedPairs.push(currentMatches);
}
for (i=0; i<matchedPairs.length; i++){
tempArray = [];
for (j=0; j<matchedPairs[i].length; j++) {
// I assume you have a new enough version of JS that you have Array.indexOf()
if (-1 === tempArray.indexOf(matchedPairs[i][j][0]))
tempArray.push(matchedPairs[i][j][0]);
if (-1 === tempArray.indexOf(matchedPairs[i][j][1]))
tempArray.push(matchedPairs[i][j][1]);
}
finalCombinations.push(tempArray);
}
for (i=0; i<finalCombinations.length; i++)
console.log(finalCombinations[i]);
// console.log shows that finalCombinations = [ [1,2,3], [9,10,11] ]
If it's not obvious how this works, follow it through with a debugger and/or pencil and paper.
I must say your question is rather unclear, but i think i got it.
In other words what you're saying is:
I have an array containing a bunch of numbers, logically they represent coordinates, it's not that the coordinates are subarrays inside the master array, is just looking them 2 by 2, but it's a linear array.
What you want is something that detects coordinates that are adjacent and generate a new array containing them.
After that you want to go thru the new arrays and generate new arrays containing unique-elements.
Well that's the question, now the answer. First, the second point depends on how far you want to go, i'm thinking it's anormal grid of x,y coordinates, but how adjacent you want to go? The following just applies to the inmediate adjacent, up to 8 points can be adjacent to a single point.
[1,1][2,1][3,1]
[1,2][2,2][3,2]
[1,3][2,3][3,3]
May that be a representation of the grid, if your master array has the [2,2] coordinate, you want to build an array that begins with that one and all adjacents you find, lets say like master array has [3,2], then you want to add it to the subarray of [2,2].
I'm really not writing the code i'm just gonna explain sorts of algorithm you could use.
To build the second point arrays, lets call them Adjacents Arrays (AA) you could:
First coordinate will always build the first AA
To find adjacents you will cycle thru the master array and perform an "Adjacency Check" to every coordinate which would be: second x == ( first x-1, x or x+1) AND second y == ( first y-1, y or y+1), if it passes then pop/push, if not... next.
In case you finish cycling thru the master array means that AA is complete, and you have to start a new AA with the next coordinate.
Repeat until master array is empty.
Then to create the unique-element-array is quite a simple cycle, i wrote a similar function that does something like that but it creates an array with the element and how many times it appears in the array (instances):
function uniqueCnt( ori) { // agroups and counts unique elements of an array, scrubs '' elements
var res = []; // resulting array, ori parameter stands for original array
for( let cntA = 0; cntA < ori.length; cntA++) {
for( cntB = 0; cntB < res.length; cntB += 2) if( ori[cntA] == res[cntB]) { res[cntB + 1]++; break; } // if it matches means it's another instance then increase that element count
if( cntB == res.length && ori[cntA] != '') res.push( ori[cntA], 1); // New element found then push it and start count
}
return res; // returns the agrouped array 0:element 1:instances...
}
If you don't want a count of instances, then you would need an even simpler function, you could try modify this one.

Categories

Resources