Add values to end of multidimensional array - javascript

I have an array of arrays and I want to be able to add values to the array every time a user hits the add button.
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
transactions[0][i] = $("date").value;
transactions[1][i] = $("transType").value;
transactions[2][i] = parseFloat( $("amount").value);
these are the snippets . . . I realize I need to work on validation (which I will do) at this point I'm more concerned with loading the arrays. The problem is the method I'm familiar with works with 1-dimensional arrays and I don't know how to replace it.
in short is it possible to reproduce this:
transactions[transactions.length] = $("date").value;
for a multidimensional array.
Thank You

Use push:
transactions[0].push( $("date").value );

You're looking for the Array.push() method. It allows you to push values on to the end of an array.
For your use case, you can do that on both levels of the array. See below:
var transactions = [];
transactions.push([]);
transactions.push([]);
transactions[0].push( $('date').value );

There is no problem for using the same approach:
transactions[0][transactions[0].length] = $("date").value;
or with push method:
transactions[0].push($("date").value);
... keeping in mind that you've initialized transactions[0] with empty array [].

Yes, just idem for multidimensional
transactions[0][transactions[0].length] = var1;

Seems a little weird you are doing:
[[array of transaction dates],[array of transaction types],[array of transaction amounts]]
Are you sure you don't want
[array of transactions, with date,type,amount properties]
?
var transactions = [];
transactions.push({'date': $("date").value, 'type': $("transType").value, 'amount': parseFloat( $("amount").value)});
var i = 0;
alert('date ' + transactions[i].date + ' type ' + transactions[i].type + ' amount ' + transactions[i].amount);

Related

Get two properties at runtime and make combination of those two properties in string (orderby orderdirection)

I have two properties "orderby" and "orderdirection" in widget.
In runtime I can adjust those properties check snip :
I want to set these properties in my rest api query.
eg: Query = "/_api/web/lists/getbytitle('" + listname + "')/items?&"$select=ID,Title,Date&$orderby=Title desc,Date asc"
Above values are hardcoded but I want to change those values in runtime. When I want to update just one value "Title desc", its easy but I want to set any number of columns at runtime.
My approach : Spilt the string first orderby.Split(",") and then make one string with both combination of "orderby orderdirection,orderby orderdirection,orderby orderdirection".
I just wanted to check if any other approach I can try here. Please suggest your suggestion here. Thank you .
a solution :
var orderby = "Title,Date,Other";
var orderdirection = "desc,asc,asc";
var ar0 = orderby.split(",");
var ar1 = orderdirection.split(",");
var res=[];
for(let i = 0; i < ar0.length; i++){
res.push(ar0[i] + ' ' + ar1[i]);
}
var result = res.join(",");
console.log(result);

ValueIterator.toArray().indexOf() returns unexpected results?

UPDATE: this is NOT a question on javascript alone, but related to the javascript implementation on the MarkLogic platform.
As the title of this question points out it is about the specific behaviour of the ValueIterator that is returned by the xdmp.userRoles() function.
I am trying to see if a user has a certain role in MarkLogic Security database, therefor I have done this :
declareUpdate();
var pid = '7610802';
// TODO validate that user can do this
var spo = 'scc-proj-' + pid + '-owner';
var spm = 'scc-proj-' + pid + '-member';
var spam = 'scc-proj-' + pid + '-adv-member';
// we need the security db Ids of these roles
var spoId = xdmp.role(spo);
var spamId = xdmp.role(spam);
var acceptedRoleIds = [spamId,spoId];
// get roleIds from sec db for this user
var userRoleIds = xdmp.userRoles('scc-user-1');
// map ValueIterator to array
var userRoleIdsArray = userRoleIds.toArray();
Now the userRoleIdsArray holds ids as unnsigned long like this:
[
"1088529792688125909",
"1452323661308702627",
"10258509559147330558",
"10161853410412530308",
"6677433310138437512",
"12773061729023600875",
"7482704131174481508",
"3191093315651213021", <<<<< this is the one!!!
"5126952842460325403",
"7089338530631756591",
"15520654661378671735",
"13041542794130379697"
]
Now indexOf() gives me -1 aka not found
userRoleIdsArray.indexOf(3191093315651213021);
OR
userRoleIdsArray.indexOf("3191093315651213021");
Gives :
-1
While
userRoleIdsArray[7]==3191093315651213021;
Gives :
true
What am I missing here? Is this not the way to use indexOf() ?
UPDATE >>> Stuff below was 'on-the-side' but turns out to be distracting from the above core question. The behaviour below is answered by #DaveCassel's comment.
btw on the created array acceptedRoleIds it is even more strange:
acceptedRoleIds.indexOf(spoId);
works
acceptedRoleIds.indexOf(3191093315651213021);
does not?
Could this large number error in javascript be relevant?
You want to find a String, not a number. Use: userRoleIdsArray.indexOf("3191093315651213021");
This works:
var array = [
"1088529792688125909",
"1452323661308702627",
"10258509559147330558",
"10161853410412530308",
"6677433310138437512",
"12773061729023600875",
"7482704131174481508",
"3191093315651213021",
"5126952842460325403",
"7089338530631756591",
"15520654661378671735",
"13041542794130379697"
];
var n = array.indexOf("13041542794130379697");
document.write(n);
output: 11
The mismatch is that ValueIterator.toArray() returns an array of Values (Value[]). When you call .indexOf, you're passing in a string or an unsignedLong rather than a value. Because the types don't match, .indexOf() doesn't report a match.
You can solve the problem by iterating through the loop. Note that I use the '==' operator rather than '==='; the type conversion is needed.
// get roleIds from sec db for this user
var userRoleIds = xdmp.userRoles('my-user');
// map ValueIterator to array
var userRoleIdsArray = userRoleIds.toArray();
var target = 15520654661378671735;
var index = -1;
for (var i in userRoleIdsArray) {
if (userRoleIdsArray[i] == target) {
index = i;
}
}
index

count the number of rows in 2d array

Description:
I am adding the data in my 2D array like the following
my_2d_array['user1'] = {'id':name,'socket':socket};
my_2d_array['user2'] = {'id':name,'socket':socket};
This 2D array keeps the record of all the connected users id and their respective sockets ...
I want to display the number of users connected .. So far to do that would be to count the number of rows in the array and display it
I have tried following:
my_2d_array[].length; // this gives nothing
my_2d_array.length; // this outputs 0 (as number)
What should I do to get the number of rows
UPDATE
I declared my array like this
var my_2d_array = [];
This could work for you
// initialize
var my_2d_array = {};
// add users
my_2d_array["user1"] = ...
my_2d_array["user2"] = ...
// get number of users
Object.keys(my_2d_array).length;
//=> 2
You should consider using users instead of my_2d_array though. It communicates better and the actual data type is an Object, not specifically an Array.
Use push method
my_2d_array.push({'id':name,'socket':socket});
my_2d_array.push({'id':name,'socket':socket});
And my_2d_array.length to get the count
It looks like you are trying to figure out how many keys are in your javascript object my_2d_array.
You should be able to use Object.keys()
Here is a JsFiddle.
var my_2d_array = {};
var name = "Hello";
var socket = "World";
my_2d_array['user1'] = {'id':name,'socket':socket};
var name = "Hello2";
var socket = "World2";
my_2d_array['user2'] = {'id':name,'socket':socket};
alert( Object.keys(my_2d_array).length );

access javascript array element by JSON object key

I have an array that looks like this
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}]
I would like to be able to access the Count property of a particular object via the Zip property so that I can increment the count when I get another zip that matches. I was hoping something like this but it's not quite right (This would be in a loop)
Zips[rows[i].Zipcode].Count
I know that's not right and am hoping that there is a solution without looping through the result set every time?
Thanks
I know that's not right and am hoping that there is a solution without
looping through the result set every time?
No, you're gonna have to loop and find the appropriate value which meets your criteria. Alternatively you could use the filter method:
var filteredZips = Zips.filter(function(element) {
return element.Zip == 92880;
});
if (filteredZips.length > 0) {
// we have found a corresponding element
var count = filteredZips[0].count;
}
If you had designed your object in a different manner:
var zips = {"92880": 1, "91710": 3, "92672": 0 };
then you could have directly accessed the Count:
var count = zips["92880"];
In the current form, you can not access an element by its ZIP-code without a loop.
You could transform your array to an object of this form:
var Zips = { 92880: 1, 91710: 3 }; // etc.
Then you can access it by
Zips[rows[i].Zipcode]
To transform from array to object you could use this
var ZipsObj = {};
for( var i=Zips.length; i--; ) {
ZipsObj[ Zips[i].Zip ] = Zips[i].Count;
}
Couple of mistakes in your code.
Your array is collection of objects
You can access objects with their property name and not property value i.e Zips[0]['Zip'] is correct, or by object notation Zips[0].Zip.
If you want to find the value you have to loop
If you want to keep the format of the array Zips and its elements
var Zips = [{Zip: 92880, Count:1}, {Zip:91710, Count:3}, {Zip:92672, Count:0}];
var MappedZips = {}; // first of all build hash by Zip
for (var i = 0; i < Zips.length; i++) {
MappedZips[Zips[i].Zip] = Zips[i];
}
MappedZips is {"92880": {Zip: 92880, Count:1}, "91710": {Zip:91710, Count:3}, "92672": {Zip:92672, Count:0}}
// then you can get Count by O(1)
alert(MappedZips[92880].Count);
// or can change data by O(1)
MappedZips[92880].Count++;
alert(MappedZips[92880].Count);
jsFiddle example
function getZip(zips, zipNumber) {
var answer = null;
zips.forEach(function(zip){
if (zip.Zip === zipNumber) answer = zip;
});
return answer;
}
This function returns the zip object with the Zip property equal to zipNumber, or null if none exists.
did you try this?
Zips[i].Zip.Count

javaqscript: 2d associative arrays 101

This is my first Q&A ever, so hopefully it's alright.
As someone who generally picks stuff up quickly, I found the information on this topic was sporadic and generally over complicated, with many people saying it simply couldn't be done. so here's it broken down very simply.
Take this scenario as an example, we have a number of form components (text boxes, buttons, etc.), all with a number of properties, all of which have values... and we want to store these in a javascript array.
Here's my tinkerings. This code doesn't explicitly answer a question, as no question was explicitly asked, however I hope you find it useful
For good measure, here also is a jsfiddle http://jsfiddle.net/cQ8Xc/
var $parent_arr = new Array();
var $child_arr = new Array();
//we can add the key => value pairs like so:
//(obviously they won't be done like this, more likely a loop for example)
//this works just fine $child_arr[$key] = $value;
$child_arr['Top'] = '12';
$child_arr['Left'] = '13';
$child_arr['Right'] = '14';
$child_arr['Bottom'] = '15';
//we can add the array to another array like so:
$parent_arr['component1'] = $child_arr;
//clear the array for reuse (note that it is obviously not nessecary to reuse the array)
$child_arr = [];
//refill it
//note that the child arrays don't have to be identical lengths or values
$child_arr['Height'] = '22';
$child_arr['Width'] = '23';
$child_arr['Colour'] = 'blue';
$parent_arr['component2'] = $child_arr;
//we can access the data like this:
alert($parent_arr['component1']['Top']);
alert($parent_arr['component2']['Colour']);
//these didn't work for me, you've likely seen them in other answers if you've been researching this topic
//alert(JSON.stringify($parent_arr['component1'], null, 4));
//alert(JSON.stringify($parent_arr['component1']));
//alert($parent_arr['component1'].join("\n"));
//the array can be looped over like so:
for(var component in $parent_arr) {
for(var propertyName in $parent_arr[component]) {
alert(component + '.' + propertyName + '=' + $parent_arr['component1'][propertyName]);
}
}

Categories

Resources