Dyamic multidimensional array in Javascript that are related to each other? - javascript

I'm still very new to array, my question is how do you links arrays one after another?
For example:
In the season array below, there are 4 keys/values, then in the designer0 and designer1 array, there are 3 keys/values pairs.
For designer0 array, it's belong to season[0] and for designer1 array, it's belong to season[1], but how do I write it in such a way that there are parent and child related?
var season = new Array();
season[0] = "summer 2013";
season[1] = "winter 2014";
season[2] = "autumn 1998";
season[3] = "spring 2005";
var designer0 = new Array();
designer[0] = "Albbs";
designer[1] = "Alexander Wang";
designer[2] = "BCBG Max Azria";
var designer1 = new Array();
designer[0] = "William Howe";
designer[1] = "Bringingthewood";
designer[2] = "Kesha";

You need a new type: "object", just like key & value.
var seasons = [{
name: "summer 2013",
designers: ["Albbs", "Alexander Wang", "BCBG Max Azria"]
}, {
name: "winter 2014",
designers: ["William Howe", "Bringingthewood", "Kesha"]
}];
object array.

If we are talking about javascript, you should remember: there are no native associative arrays in it. Since your season already contains data, the only way to maintain subordination is to create associative array, where season name will be a key and designers data - a value.
However, you can use array of objects to create desired data structure:
var seasons = [
{
"index" : 0,
"name" : 'summer 2013',
"designers": ['Albbs', 'Alexander Wang']
},
{
"index" : 1,
"name" : 'winter 2014',
"designers": ['William Howe', 'Kesha']
}
];
-see this fiddle to check how to work with such data.

You can use JSON:
[
{
"season":"summer 2013",
"designer1":"Albbs",
"designer2":"William Howe"
},
{
"season":"winter 2014",
"designer1":"Alexander Wang",
"designer2":"Bringingthewood"
}
]

Add a new array that links them and then refer to that array:
seasonal_designers =
[
0 = {designer0[0],designer0[1],designer0[2]}
1 = {designer1[0],designer1[1],designer1[2]}
]
Now get your stuff like this:
value=''
for(i in seasonal_designers[specify number])
value+=seasonal_designers[specify number][i] + ' (the designers id '+ i +')'

Related

Procedure to add element to JSON array

I have been trying to add an element to a JSON array, in which the JSON array is designed with the following attributes:
/*
var courses = [{
"dept": "CSC",
"id": "3102",
"instructor": "Kooima",
"Location": "230 Turead"
}
]
and the JavaScript code segment that performs the task is implemented as:
var newCourse = {};
courses.push(newCourse);
var count = courses.length - 1;
courses[count].dept = dept;
courses[count].id = num;
courses[count].instructor = prof;
courses[count].Location = loc;
However, I believe this may not be in the correct order/missing further code to properly add the element to the list, and wanted to make sure I was possibly not neglecting an essential component.
What you did will work fine. Personaly I prefer the following way;
var newCourse = {};
newCourse.dept = dept;
newCourse.id = num;
newCourse.instructor = prof;
newCourse.Location = loc;
courses.push(newCourse);
There is nothing like JSON array, It's simple javascript array which you can create in the following manner.
Just push the new course every time
courses.push({
"dept": dept,
"id": id,
"instructor": prof,
"Location": loc
});
Quick and simple
courses.push({
"dept": dept,
"id": num,
"instructor": prof,
"Location": loc
});

A better way than chaining _.groupBy?

When I do this I get an array which stores the data as grouped by the month and day of the date but not by the year (I am doing this to get maximum, minimum, and average values for each day there is data for)
The problem is that the array stores an array of 2-3 values for that day and month within the date which is the key value. Those 2-3 indices each have an array of length one that holds a reference to an object which has the actual data point (level) I need. The object contains three attributes, date, id (which is always null), and level which is a float.
I either need to find a way so those 2-3 indices hold the object directly, or find a way that _.each can access the level.
Any thoughts?
var groupedData = _.groupBy(data, "date");
var groupedLevels = _.groupBy(groupedData, function (points, date) {
var dateParsed = parseDate(date);
var month = dateParsed.getMonth();
var day = dateParsed.getDate();
var monthDay = month + "-" + day;
return monthDay;
});
_.each(groupedLevels, function (points, date) {
var levels = _.map(_.pluck(points, "level"), parseFloat);
minimum.push([ date, R.min(levels) ]);
maximum.push([ date, R.max(levels);
var averageLevel = R.sum(levels) / levels.length;
average.push([date, averageLevel]);
})
So the data, as is, which is the original input looks like this (a sample piece):
[ { date: "2009-01-01",
id: null,
level: "0.08",
},
// ...
]
Currently, groupedData is this:
{ "2009-01-01":
[ { date: "2009-01-01",
id: null,
level: "0.08"
}
],
// ...
}
groupedLevels looks like this, for example:
{ "0-1":
[ [ { date: "2009-01-01".
id: null,
level: "0.08"
}
],
// ...
],
// ...
}
I want to skip having all the arrays of length one and just have the object stored there.
I think you can fix the immediate issue by replacing this line:
var levels = _.map(_.pluck(points, "level"), parseFloat);
With this:
var levels = _.map(_.pluck(points[0], "level"), parseFloat);
...but I think the real problem might be that you're doing groupBy twice when you don't need to. This single groupBy ought to be equivalent, but without the extra nested array:
var groupedLevels = _.groupBy(data, function(item) {
var dateParsed = parseDate(item.date);
var month = dateParsed.getMonth();
var day = dateParsed.getDate();
return month + '-' + day;
});
With this, your each should work as expected.

How can I find the frequency of each member in my data set

I am working to fetch and analyze a large data set.
I want to know how many each value is appearing in the data set.
Let's give a small example to clarify things.
[
{"Year": "1997", "Company": "Ford", "Model": "E350", "Length": "2.34"},
{"Year": "2000", "Company": "Mercury", "Model": "Cougar", "Length": "2.38"}
{"Year": "2001", "Company": "Ford", "Model": "Cougar", "Length": "2.38"}
]
I don't know exactly what the values that I am having, but I want to hash it to get the results this way.
[
{"Value": "Ford", "Frequency": 2},
{"Value": "Mercury", "Frequency": 1},
]
In case it's not dynamic and I know the the values, I will do it this way:
var filteredCompany = data.filter(function(a) {
return /Ford/i.test(a.Company).lenght;
});
But, I have a very large data set (900 Mbo), I need to make this process in a very dynamic way.
UPDATE
var dataset = {}
d3.csv(link, function(data) {
dataset = data;
});
//Fetch data
var frequency = {};
var datasetlength = dataset.length;
for(var i = 0; i < datasetlength; i++){
var current = dataset[i];
if(!frequency.hasOwnProperty(current.company)) frequency[current.company] = 0;
frequency[current.company]++;
}
What you can do is loop through all the entries, and gather them into an object where the key is the name and the value is the count. The initial data will look like this:
{
"Ford" : 2,
"Mercury" : 1
}
You can do a reduce, passing through an object:
var frequency = hugeData.reduce(function(freq,current){
var currentCompany = current.Company;
if(!freq.hasOwnProperty(currentCompany)) freq[currentCompany] = 0;
freq[currentCompany]++;
return freq;
},{});
But reduce is ES5 and sometimes slow. You can do a plain loop:
var frequency = {};
var hugeDataLength = hugeData.length;
for(var i = 0; i < hugeDataLength; i++){
var current = hugeData[i];
var currentCompany = current.Company;
if(!frequency.hasOwnProperty(currentCompany)) frequency[currentCompany] = 0;
frequency[currentCompany]++;
}
Now that we have reduced the data into a much more manageable size, you can loop through the frequency data and turn it into an array, moving down the key and value into an object.
var chartData = Object.keys(frequency).map(function(company){
var value = frequency[company];
return {
Value : company,
Frequency : value
}
});
A running demo can be seen here.
I did a similar feat in the past few months, and your browser's debugger is a very handy tool for this job, especially the CPU profiler. You can pin down which operations are actually causing the lag.
I'm not sure if this is the most efficient method of going through that much data (then again, Javascript was not made for big data so efficiency shouldn't be on your mind).
Basically I would approach this looping through all the data with an associative array keeping track of the frequency. If the current data.Company is not in the associative array, it'll add it on to the array as a key and then input the frequency of one. If it is found as a key in the array, it'll increment the frequency by 1.
Example

creating a json object with variable fields

I am currently trying to use morris.js to create a graph. I am given one JSON object and need to make it look like another. Morris.js needs an array to look like this
var day_data = [
{"period": "2012-10-01", "licensed": 3407, "sorned": 660},
{"period": "2012-09-17", "licensed": 3171, "sorned": 660},
{"period": "2012-09-16", "licensed": 3171, "sorned": 676},
{"period": "2012-09-15", "licensed": 3201, "sorned": 656},
{"period": "2012-09-10", "licensed": 3215, "sorned": 622}
];
here is the link if the object appears confusing. It should be a shortened version of the first graph's data on their site http://oesmith.github.com/morris.js/
. Its pretty simple, period is the x coordinate, and licensed and sorned are y coordinates for their corresponding lines.
Here is the data I am given
var trendline = {"command":[
{"keyValuePairs":["2012-08-10 22:00:00|1884978","2012-08-10 21:00:00|3135378","2012-08-10 18:00:00|2541438","2012-08-09 20:00:00|647082","2012-08-10 19:00:00|3194772","2012-08-09 16:00:00|2782140","2012-08-10 20:00:00|3669924"],
"keyword":"Obama"},
{"keyValuePairs":["2012-08-10 22:00:00|1884978","2012-08-10 21:00:00|3135378","2012-08-10 18:00:00|2541438","2012-08-09 20:00:00|647082","2012-08-10 19:00:00|3194772","2012-08-09 16:00:00|2782140","2012-08-10 20:00:00|3669924"],
"keyword":"Romney"}]}
I need to extract all the data from keyValuePairs and associate it with its keyword so looks like the first array
{"period": "2012-10-01", "Obama": 1884978, "Romney": 1884978},
...
...
I know to get the data from the trendline JSON object but i don't know how to construct a new JSON object that the morris.js plugin could use. More specifically i don't know how to create a JSON object using variables.
trendline.dog = [cat];
Will create a json object with the field dog set to the value cat. However, i need to take each keyword(obama,romney...etc) and have a field associated with it and set a value to it. Since i don't know the number of fields or what their names are, I don't know how to create this object.
Assume I cannot change the way I am given data as I do not write that part. Also I could be given only two keywords (obama/romney) like in my example or i could be given any number of keywords for the y-values.
Sorry for the long length. Any help would be appreciated. Thanks for your time.
Here is your Christmas present.
<script type="text/javascript">
var trendline =
{
"command": [
{
"keyValuePairs":
[
"2012-08-10 22:00:00|1884978",
"2012-08-10 21:00:00|3135378",
"2012-08-10 18:00:00|2541438",
"2012-08-09 20:00:00|647082",
"2012-08-10 19:00:00|3194772",
"2012-08-09 16:00:00|2782140",
"2012-08-10 20:00:00|3669924"
],
"keyword": "Obama"
},
{
"keyValuePairs":
[
"2012-08-10 22:00:00|1884978",
"2012-08-10 21:00:00|3135378",
"2012-08-10 18:00:00|2541438",
"2012-08-09 20:00:00|647082",
"2012-08-10 19:00:00|3194772",
"2012-08-09 16:00:00|2782140",
"2012-08-10 20:00:00|3669924"
],
"keyword": "Romney"
}]
}
var cmd = trendline.command,
day_data = [],
split,
date,
num,
obj;
//
for (var i = 0; i < cmd.length; i++) {
//
if (i == 1) { break; };
//
for (var ii = 0; ii < cmd[i].keyValuePairs.length; ii++) {
//debugger
split = cmd[i].keyValuePairs[ii].split('|');
date = split[0].substring(0, split[0].indexOf(' '));
num = split[1];
obj = {};
obj['period'] = date;
//Can 1
obj[cmd[i].keyword] = num;
//
split = cmd[i + 1].keyValuePairs[ii].split('|');
num = split[1];
//Can 2
obj[cmd[i + 1].keyword] = num;
//
day_data.push(obj);
};
};

creating list of objects in Javascript

Is it possible to do create a list of your own objects in Javascript? This is the type of data I want to store :
Date : 12/1/2011 Reading : 3 ID : 20055
Date : 13/1/2011 Reading : 5 ID : 20053
Date : 14/1/2011 Reading : 6 ID : 45652
var list = [
{ date: '12/1/2011', reading: 3, id: 20055 },
{ date: '13/1/2011', reading: 5, id: 20053 },
{ date: '14/1/2011', reading: 6, id: 45652 }
];
and then access it:
alert(list[1].date);
dynamically build list of objects
var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
listOfObjects.push(singleObj);
});
here's a working example http://jsfiddle.net/b9f6Q/2/
see console for output
Maybe you can create an array like this:
var myList = new Array();
myList.push('Hello');
myList.push('bye');
for (var i = 0; i < myList .length; i ++ ){
window.console.log(myList[i]);
}
Going off of tbradley22's answer, but using .map instead:
var a = ["car", "bike", "scooter"];
a.map(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
return singleObj;
});
Instantiate the array
list = new Array()
push non-undefined value to the list
var text = list.forEach(function(currentValue, currentIndex, listObj) {
if(currentValue.text !== undefined)
{list.push(currentValue.text)}
});
So, I'm used to using
var nameOfList = new List("objectName", "objectName", "objectName")
This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

Categories

Resources