Javascript - Change array values with if statement - javascript

I am working on a jquery form file that uses an array to populate a dropdown of sizes based on the selection of the material. This works fine but now we are adding an additional dropdown and we need to have different values in the array based on that selection.
this is the part of the current working code:
var Material = new Array();
Material['UNC'] = new Array('40', '32');
Material['UNF'] = new Array('10', '24');
This is basically what I am trying to, not sure how:
if($("#style").val() == "long") { var Material = new Array();
Material['UNC'] = new Array('45', '35');
Material['UNF'] = new Array('15', '29');} else {
var Material = new Array();
Material['UNC'] = new Array('40', '32');
Material['UNF'] = new Array('10', '24');}
I'm not having any luck, I'm not super familiar with Javascript functions. Thanks

One way:
var isLong = $('#style').val() === 'long';
var material = {};
material.UNC = (isLong) ? [45, 35] : [40, 32];
material.UNF = (isLong) ? [15, 29] : [10, 24];
Another way:
var isLong = $('#style').val() === 'long';
var material = {};
if (isLong) {
material.UNC = [45, 35];
material.UNF = [15, 29];
}
else {
material.UNC = [40, 32];
material.UNF = [10, 24];
}
As Felix Kling points out, it is better to use an object over an array for material. I've also used JavaScript convention of a lowercase variable name. Instead of using new Array use [] and instead of new Object, you can use {}.

You just need to move the declaration of the Material variable outside the blocks:
var Material = new Array();
if($("#style").val() == "long") {
Material['UNC'] = new Array('45', '35');
Material['UNF'] = new Array('15', '29');
} else {
Material['UNC'] = new Array('40', '32');
Material['UNF'] = new Array('10', '24');
}
However, as others have pointed out, you should be using an object rather than an array for these kinds of non-numeric indexes. You should also use object and array notation:
var Material = {};
if($("#style").val() == "long") {
Material['UNC'] = ['45', '35'];
Material['UNF'] = ['15', '29'];
} else {
Material['UNC'] = ['40', '32'];
Material['UNF'] = ['10', '24'];
}

Related

Sort a more dimensional array by specific order

I have been thinking for quite some time now on how to sort my array in Javascript in the way I want to, trying various methods and I can't come up with a solution so I decided to ask here...
So in a nutshell, my array looks as complex as that:
var englishvoc = new Array();
englishvoc[0] = new Array();
englishvoc[0][0] = "beautiful";
englishvoc[0][1] = new Array();
englishvoc[0][1][0] = 0;
englishvoc[0][2] = 2;
englishvoc[1] = new Array();
englishvoc[1][0] = "nice";
englishvoc[1][1] = new Array();
englishvoc[1][1][0] = 0;
englishvoc[1][2] = 2;
englishvoc[2] = new Array();
englishvoc[2][0] = "get";
englishvoc[2][1] = new Array();
englishvoc[2][1][0] = 9;
englishvoc[2][1][1] = 7;
englishvoc[2][1][2] = 2;
englishvoc[2][2] = 1;
The way I want this array to be sorted is just by the English word in there, so that the order of them become "beautiful", "get", "nice", while moving the whole first dimensions of the array. Result should be:
alert(englishvoc) //Returns: '"beautiful",0,2,"get",9,7,2,1,"nice",0,2'
In addition to that, it would be great if this sorting system would not be case sensitive...
Maybe someone has a solution for that complicated array sorting?
Thanks in advance!
You could try sort() and localeCompare()
var englishvoc = new Array();
englishvoc[0] = new Array();
englishvoc[0][0] = "beautiful";
englishvoc[0][1] = new Array();
englishvoc[0][1][0] = 0;
englishvoc[0][2] = 2;
englishvoc[2] = new Array();
englishvoc[2][0] = "nice";
englishvoc[2][1] = new Array();
englishvoc[2][1][0] = 0;
englishvoc[2][2] = 2;
englishvoc[7] = new Array();
englishvoc[7][0] = "get";
englishvoc[7][1] = new Array();
englishvoc[7][1][0] = 9;
englishvoc[7][1][1] = 7;
englishvoc[7][1][2] = 2;
englishvoc[7][2] = 1;
englishvoc.sort((a,b)=>a[0].localeCompare(b[0]))
console.log(englishvoc.join())
To me it looks like you are trying to represent an object array as multi dimensional array. I think you should be able to represent like below.
[{
name: "beautiful";
data: {
val1: [0]
val2: [1]
}
},
{
name: "nice";
data: {
val1: [0]
val2: [1]
}
},
{
name: "get";
data: {
val1: [9]
val2: [7,2]
}
}]
This array of object should be easily sortable.

How can I create an new array for each specific data in a loop in javascript?

I have this function:
flotLinea:function(tareas){
var self = this;
console.info(tareas);
var aTar = new Array();
for(var i = 0;i<tareas.length;i++){
var val = new Array(new Date(tareas[i].fecha_registro),tareas[i].porcentaje);
aTar.push(val);
}
console.info(aTar);
},
Using console.info(tareas); print this :
And using console.info(aTar); print :
(The data from tareas always is changing because the data comes from a dropdown)
I need create an new array for each id_usu using the same data , how can I do this?
For example in this case I need an array for id_usu = 4 ( are two id_usu = 4, so i need the data where id_usu = 4) , one array with id_usu = 6 and one array with id_usu = 9
I need do this , because this data are for a chart, so, after , each user ( id_usu ) will be a different color in that chart.
From whatever I have understood form your problem statement and the code you have provided, I've provided a solution below.
flotLinea:function(tareas){
var self = this;
console.info(tareas);
var aTar = new Array();
var idArray = [];
for(var i = 0;i<tareas.length;i++){
if(idArray.indexOf(tareas[i].id_usu) == -1){
var val = new Array(new Date(tareas[i].fecha_registro),
tareas[i].porcentaje);
idArray.push(tareas[i].id_usu);
aTar.push(val);
}
else{
for(var j = 0; j < aTar.length; j++){
if(tareas[i].id_usu == aTar[j][0].id_usu){
aTar[j].length = new Array(new Date(tareas[i].fecha_registro)
,tareas[i].porcentaje);
}
}
}
}
console.info(aTar);
}
I'm using Brute-Force kind of solution, performance can always be increased.
I've created on new array above as idArray to hold the unique id_usus, and am comparing if the current tareas[i].id_usu already is there in that array, if not push the new value to aTar array and tareas[i].id_usu to idArray, else loop over the aTar array and find the array which already has the object with the current tareas[i].id_usu and push the new values at aTar[j].length.

three.js: Access Scene Objects by Name or ID

I'm generating objects from an array which I've defined like this (It's not limited to these three):
var links = [['Linkedin','img/linkedin.png','-300','-230', '600'],
['Google+', 'img/google.png', '0', '-230', '600'],
['Twitter', 'img/twitter.png', '300', '-230', '600']];
Now it goes through the each loop to create and add the objects to the scene by Three.JS like this:
$.each(links, function(i, item) {
var thisItemTexture = THREE.ImageUtils.loadTexture(item[1]);
thisItemGeo = new THREE.CubeGeometry(60, 60, 60,1 ,1 , 1);
thisItemMat = new THREE.MeshBasicMaterial({map: thisItemTexture });
thisItem = new THREE.Mesh(thisItemGeo, thisItemMat);
scene.add(thisItem);
thisItem.position.x = item[2];
thisItem.position.y = item[3];
thisItem.position.z = item[4];
thisItem.castShadow = true;
thisItem.receiveShadow = true;
});
The question is: How can I access the objects that I've made in the each loop above?
You can do this:
myObject.name = "objectName";
...
var object = scene.getObjectByName( "objectName" );
or to recursively search the scene graph
var object = scene.getObjectByName( "objectName", true );
Alternatively, you can search by ID.
var object = scene.getObjectById( 4, true );
three.js r.61

How to assign indexes to variable names inside FOR LOOP?

How to assign indexes to variable names? For instance, project0, project1, project2, etc?
for (var i=0; i<data.length; i++)
{
var project+i = new GanttProjectInfo(1, "Applet redesign", new Date(2010, 5, 11));
var parentTask+i = new GanttTaskInfo(1, "Old code review", new Date(2010, 5, 11), 208, 50, "");
project1.addTask(parentTask+i);
// Load data structure
ganttChartControl.addProject(project+i);
// Build control on the page
}
Just as #JaredFarrish suggested, you can simply use an array to store all the projects. Create them and add them to the array before the variable gets overwritten:
var projects = [];
for (var i = 0; i < data.length; i++) {
var project = new GanttProjectInfo(1, "Applet redesign", new Date(2010, 5, 11));
var parentTask = new GanttTaskInfo(1, "Old code review", new Date(2010, 5, 11), 208, 50, "");
project.addTask(parentTask);
ganttChartControl.addProject(project);
// Push this project to the array to save it
projects.push(project);
}
// Need to access the first project?
projects[0].foo();
using eval()
eval(("varname" + i) + " = " + 5 + i);
but using eval is not really recommended there is always a way around for what you are trying to do.

Javascript 'object expected' when working with Google Visualization API

Hey everyone, so I am working on creating a small class to help me work with the Google visualization API. You can see how it works here...
http://code.google.com/apis/visualization/documentation/gallery/annotatedtimeline.html
Here is google's implementation.
google.load('visualization', '1', {'packages':['annotatedtimeline']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Sold Pencils');
data.addColumn('string', 'title1');
data.addColumn('string', 'text1');
data.addColumn('number', 'Sold Pens');
data.addColumn('string', 'title2');
data.addColumn('string', 'text2');
data.addRows([
[new Date(2008, 1 ,1), 30000, undefined, undefined, 40645, undefined, undefined],
[new Date(2008, 1 ,2), 14045, undefined, undefined, 20374, undefined, undefined],
[new Date(2008, 1 ,3), 55022, undefined, undefined, 50766, undefined, undefined],
[new Date(2008, 1 ,4), 75284, undefined, undefined, 14334, 'Out of Stock','Ran out of stock on pens at 4pm'],
[new Date(2008, 1 ,5), 41476, 'Bought Pens','Bought 200k pens', 66467, undefined, undefined],
[new Date(2008, 1 ,6), 33322, undefined, undefined, 39463, undefined, undefined]
]);
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(data, {displayAnnotations: true});
Here is the class I made that I am having issues with.
The class makes adding data to the graph a little easier and better for what I am trying to do. Basically, instead of making columns with a bunch of undefined values, the class does it for you, and you don't have to keep track of the location/value of each column.
function GraphManager(dataTable)
{
this.graphData = new Array();
this.dataTable = dataTable;
this.titleFinder = new Object(); // used to keep track of the indices
this.dataTable.addColumn('date', 'Date');
this.addSet = function(title)
{
var setCount = (this.dataTable.getNumberOfColumns() -1) / 3; //used for the column name
var place = this.dataTable.getNumberOfColumns();
this.titleFinder[title] = place; //the title of the column and its location
this.dataTable.addColumn('number', title);
this.dataTable.addColumn('string', 'title' + setCount);
this.dataTable.addColumn('string', 'text' + setCount);
}
this.addPoint = function(title, date, number)
{
//this function finds the location of the category
//and inserts a column with data at the location
var place = titleFinder[title]; //get the location
var column = new Array(dataTable.getNumberOfColumns());
column[0] = date;
column[place] = number;
for (var i = 0;i<place; i++)
{
column[i] = undefined;
}
for (var i = place + 1; i<dataTable.getNumberOfColumns(); i++)
{
column[i] = undefined;
}
var next = this.graphData.length;
this.graphData[next] = column;
data.addRows(graphData);
}
}
And then this code can be used to do the same thing with a fewer amount of code.
function printGraph()
{
var data = new google.visualization.DataTable();
var gm = new GraphManager(data);
var title = "testcategory";
gm.addSet(title);
gm.addPoint(title, new Date[2010, 5, 10], 100);
gm.addPoint(title, new Date[2010, 6, 10], 200);
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(gm.dataTable, {displayAnnotations: true});
}
With this HTML body
<input type="button" onclick="printGraph()" value="Draw Graph">
<div id='chart_div' style='width: 800px; height: 350px;'></div>
The issue: I am getting an "Object expected" error on the line gm.addSet(title). Basically, I am not able to use the class GraphManager. What am I doing wrong here?
Isn't supposed to be "dataTable" instead of "tableData"?
for (var i = place + 1; i<tableData.count; i++)
{
column[i] = undefined;
}
I don't know, as per:
http://code.google.com/apis/visualization/documentation/reference.html#DataTable
count is not an attribute, but I see you referring to it many places in your code:
var column = new Array(dataTable.count)
There is dataTable.getNumberOfColumns() however
Ok, I figured out the problem. Basically I had left out a bunch of "this" statements, and when I created a new date I used a bracket instead of a parentheses. I also realized that when I added a new set of data, I needed to go through the old data to add the empty columns. Here is the finished code if anyone is interested... It's pretty useful if you are adding data at different dates or if you don't know how many data sets you will have.
function GraphManager(adataTable)
{
this.graphData = new Array();
this.dataTable = adataTable;
this.titleFinder = new Object(); // used to keep track of the indices
this.dataTable.addColumn('date', 'Date');
this.addSet = function(title)
{
var setCount = (this.dataTable.getNumberOfColumns() -1) / 3; //used for the column name
var pointsCount = this.graphData.length;
var place = this.dataTable.getNumberOfColumns();
this.titleFinder[title] = place; //the title of the column and its location
this.dataTable.addColumn('number', title);
this.dataTable.addColumn('string', 'title' + setCount);
this.dataTable.addColumn('string', 'text' + setCount);
var newCount = this.dataTable.getNumberOfColumns();
for (var i = 0; i<pointsCount; i++)
{
for (var j=place; j<newCount; j++)
{
this.graphData[i][j] = undefined;
}
}
}
this.addPoint = function(title, date, number)
{
//this function finds the location of the category
//and inserts a column with data at the location
var place = this.titleFinder[title]; //get the location
var column = new Array(this.dataTable.getNumberOfColumns());
column[0] = date;
column[place] = number;
for (var i = 1;i<place; i++)
{
column[i] = undefined;
}
for (var i = place + 1; i<this.dataTable.getNumberOfColumns(); i++)
{
column[i] = undefined;
}
var next = this.graphData.length;
this.graphData[next] = column;
this.dataTable.addRows(this.graphData);
}
}
And its as easy to use as this:
var data = new google.visualization.DataTable();
var gm = new GraphManager(data);
var title = "testcategory";
var title2 = "cat";
gm.addSet(title);
gm.addPoint(title, new Date(2010, 5, 10), 100);
gm.addPoint(title, new Date(2010, 6, 10), 200);
gm.addPoint(title, new Date(2010, 2, 10), 300);
gm.addSet(title2);
gm.addPoint(title2, new Date(2010, 6, 10), 100);
gm.addPoint(title2, new Date(2010, 2, 10), 500);
var chart = newgoogle.visualization.AnnotatedTimeLine(document.getElementById('chart_div'));
chart.draw(gm.dataTable, {displayAnnotations: true});

Categories