Convert Array in Map or 2D Array - javascript

So I basically have a gradebook that is a .csv file and is formatted like this
name, grade
name, grade
I am looking for the best way to split my array so that I can access each independently but they are still related to each other.
function handleFileLoad(event){
var baseText = event.target.result;
var splitString = baseText.split("\r\n");
console.log(splitString)
}
This is my current code so it currently splits the original text into the array properly but the output is like this
0: "Name,Percent"
​
1: "Eddie,65.95"
​
2: "Alice,56.98"
​
3: "Delmar ,96.1"
​
4: "Edmund ,78.62"
when I want it like
0: "Name" "Percent"
​
1: "Eddie" "65.95"
​
2: "Alice" "56.98"
​
3: "Delmar" "96.1"
4: "Edmund" "78.62"

Add this code:
for(let i = 0; i < splitString.length; i++){
splitString[i] = splitString[i].split(",")
}

Related

Get value of array in javascript

I have this list of node :
10, 16 , 21, 26, fils_de_10, fils_de_16, fils_de_21 are on the same level and files_de_10 is supposed to be the child of 10 in term of the structure of my project.
I want to create a function checkChild(node,id) , so example when i call checkChild(_obj,10), It will return 15,14,13,11,12 that are the child and sub child of 10.
I have been trying to come up with a recursive function but it becomes messy.
It would be good if anyone already has some similar function.
Edited : This is the json data of the node :
var _str = '{"10":{"0":"0","1":"DISPONIBILITES","2":"t","style":"font-weight: bold;"},"16":{"0":"0","1":"TRESORERIE NETTE","2":"t","style":"font-weight: bold;"},"21":{"0":"0","1":"COMPTES","2":"t","style":"font-weight: bold;"},"26":{"0":"0","1":"LIGNE DE CREDIT BNP/HSBC","2":"f","style":"color:black;"},"fils_de_21":{"22":{"0":"21","1":"EXASOLAR SA","2":"f","style":"color:black;"},"23":{"0":"21","1":"EXASOLAR CORP","2":"f","style":"color:black;"},"24":{"0":"21","1":"EXASOLAR SARL","2":"f","style":"color:black;"},"25":{"0":"21","1":"EXASOLAR SL","2":"f","style":"color:black;"}},"fils_de_10":{"13":{"0":"10","1":"Disponibilits France","2":"t","style":"font-weight: bold;"},"14":{"0":"10","1":"Dispo exasolar SL","2":"f","style":"color:black;"},"15":{"0":"10","1":"Dispo exasolar corp","2":"f","style":"color:black;"},"fils_de_13":{"11":{"0":"13","1":"Dispo exasolar SA","2":"f","style":"color:black;"},"12":{"0":"13","1":"Dispo exasolar sarl","2":"f","style":"color:black;"}}},"fils_de_16":{"17":{"0":"16","1":"Trso nette exasolar SA","2":"f","style":"color:black;"},"18":{"0":"16","1":"Trso nette exasolar SL","2":"f","style":"color:black;"},"19":{"0":"16","1":"Trso nette exasolar corp.","2":"f","style":"color:black;"},"20":{"0":"16","1":"Trso nette exasolar sarl","2":"f","style":"color:black;"}}}';
Not sure if what you want is something like this.
What I've done is to check inside the function is the current item key is something starting with fils_de_, if it is, then we call the function recursively. If not, we simply add the value to our list array.
Take a look and let me know if that works for you.
Cheers!
var my_data = {
10: {
0: "0",
1: "blabla",
2: "t"
},
fils_de_10: {
13: {
0: "10",
1: "blabla 10_13",
2: "t"
},
14: {
0: "10",
1: "blabla 10_14",
2: "t"
},
15: {
0: "10",
1: "blabla 10_15",
2: "t"
},
fils_de_13: {
11: {
0: "10",
1: "blabla 10_11",
2: "t"
},
12: {
0: "10",
1: "blabla 10_12",
2: "t"
}
}
}
};
function checkChild(node,id) {
var list = [];
if(node['fils_de_'+id])
for (var item in node['fils_de_'+id])
if(item.match(/fils\_de\_(\d+)/))
list.push(...checkChild(node['fils_de_'+id], item.split('_')[2]));
else
list.push(item);
else
for (var item in node)
if(item.match(/fils\_de\_(\d+)/))
list.push(...checkChild(node[item], id));
return list;
}
console.log(checkChild(my_data, 10));
console.log(checkChild(my_data, 13));
If i get it right, what you need is a simple Breadth-first tree traversing. Check out the well known algorithm - it should work.
In steps you should:
Build the name of the node you want to examine ("fils_de_10" in you example).
Traverse the tree until you find this node.
Traverse a subtree of this node and store all leaves as your result.
Hope it works.

jQuery Convert Object Array to Array with keys

I have an object array which looks like:
Object {0: "Ma. Jessa Martinez", 1: "Edwin Cuevas", 2: "Gerum Generol", 3: "Roy delos Reyes", 4: "Hannah Montecillo", 5: "Ralph Turla", 6: "Edralyn Danabar", 7: "Angelo Sto Domingo", 8: "Rhina Dela Cruz", 9: "Ricardo Camara", 10: "Joene Floresca"}
And I want to convert in array like:
[[0,"Ma. Jessa Martinez"],[1,"Edwin Cuevas"],[2,"Gerum Generol"], and so on]
I tried using
var myobj_array= $.map(ticks, function(value, index) {
return [value];
});
But it only return the values with no keys:
["Ma. Jessa Martinez", "Edwin Cuevas", "Gerum Generol", "Roy delos Reyes", "Hannah Montecillo", "Ralph Turla", "Edralyn Danabar", "Angelo Sto Domingo", "Rhina Dela Cruz", "Ricardo Camara", "Joene Floresca"]
Is there other way? I've search already in google I can't find a similar thing.
EDIT To be clear where my object array came from, I added this for reference. It came from an ajax request and already sorted:
var ticks = {};
$.each(result, function(key,value) {
ticks[key] = value.name;
});
Use instead :
var myobj_array= $.map(ticks, function(value, index) {
return [[index,value]];
});
console.log(myobj_array);
#PinkTurtle point is important, because we may pay attention to the performance or use vanillajs instead jQuery.
However if the object structure use instead :
{80: "Ma. Jessa Martinez", 12: "Edwin Cuevas"}
and we process with only the index (and we retrieve it like arr[80] would be undefined, only if we use arr[0] would work, but the index of the user is not 0 , is 80).
Or just use normal js:
var arr = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
arr.push([i, obj[i]]);
}
}
You may create a new Javascript object and return as follow:
var myobj_array= $.map(ticks, function(value, index) {
Var obj=[[index,value]];
return obj;
});

javascript array only first character displayed

I'm currently working on a ckeditor plugin, the selectbox gets its data from a DB and I can only get the first character to appear in the selectbox.
get_pages.php
$query = selectQuery('
SELECT title, pageID
FROM `page_info`
WHERE partnerID =?',array($partnerId));
$test = '';
foreach ($query as $key => $value) {
$test .= $value['title'].",";
}
Plugin.js
var pages = $.post(
"/action/ac_select_pages.php",
{ pid: "1" },
function(data) {
return (data);
}
);
pages = pages.responseText.split(',');
my variable:
pages: Array[31]
0: "Home"
1: "Control Panel"
2: "24/7 Support"
3: "Script / Databases"
4: "Last Announcment"
5: "E-mail: No Limit"
6: "Webmail & Push Mail"
and so on..
what I do to make my selectbox:
{
type : 'select',
id : 'moreinfo',
label : 'Meerinfo Link',
style : 'width:300px;',
items : pages ,
setup : function( element )
{
this.setValue( element.getAttribute( "moreinfo" ) );
},
commit : function( element )
{
var id = this.getValue();
// If the field is non-empty, use its value to set the element's id attribute.
if ( id )
element.setAttribute( 'moreinfo', id );
// If on editing the value was removed by the user, the id attribute needs to be removed.
// http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dom.element.html#removeAttribute
else if ( !this.insertMode )
element.removeAttribute( 'moreinfo' );
}
}
As you can see I simply put the array in the items , but it shows only the first character
So what am I doing wrong?
So, to summarize...
split() Splits a String object into an array of strings by separating the string into substrings.
So, presumably your pages.responseText looks like this:
Home,Control Panel,24/7 Support,Script / Databases,Last Announcment,E-mail: No Limit,Webmail & Push Mail
Which means that after doing pages = pages.responseText.split(',');, pages looks like this (an array):
["Home", "Control Panel", "24/7 Support", "Script / Databases", "Last Announcment", "E-mail: No Limit", "Webmail & Push Mail"]
According to your previous comment, this works:
var pages = [{0: 'Home', 1: 'Control Panel', ...}];
As you can see (an array with multiple values):
["Home", "Control Panel", ...]
is not the same as (an array with one object with several properties):
[{0: 'Home', 1: 'Control Panel', ...}]
If all of this is still true, something like this should work:
var pagesObject = {};
for (var i=0, max=pages.length; i<max; i += 1) {
pagesObject[i] = pages[i];
}
var correctPages = [ pagesObject ];
Demo here: http://jsbin.com/ikazes/1/edit
Based on the for loop of Ayman Sadadi I got it finally right:)
// page1, 1,00,page2, 12,00,page3, 23 \\
pages = pages.responseText.split(',00,');
// ["page1, 1","page2, 12","page3, 23"] \\
var a = [];
a[0] = '';
for (var b = 0; b < pages.length; b++) {
var c = pages[b].split(', ');
var pageName = c[0];
var pageId = c[1];
a[b] = [ pageName, c ];
};
a is now:
a: Array[31]
0: Array[2]
0: "Home"
1: Array[2]
0: "Home"
1: "1"
length: 2
__proto__: Array[0]
1: Array[2]
0: "Control Panel"
1: Array[2]
0: "Control Panel"
1: "152"
length: 2
__proto__: Array[0]
this is the same as the required [['Home']['Control Panel']].
If I use that as my items it works correctly.
previous conversation:
try to put local data in the select. var pages = [{0: 'Home', 1: 'Control Panel', ...}];. ...
I tryed that :) and it works, but as the pages are constantly added and deleted i can't hard code the pages in the select
Ayman Safadi: According to your previous comment, this works...
Only if I hard code it like [['home']['Control Panel']] it works. [{0: 'Home', 1: 'Control Panel', ...}] did not work. I'm sorry to be a little unclear about what I meant.
Thank you for helping me with my problem.
Credits go to Ayman Safadi / pbaris :)

Javascript, check multiple arrays for number

I'm looking for the best solution here, i've got an idea but thinking it could be done prettier.
I'm making an simple weather application. And i'm using Yahoo Weather api were they have got codes for weather conditions.
Depending on the condition i'm giving a code. Now, there are 50 codes and i've categorised them into 5 categories. In my case ex. my categori Snow contains 15 of Yahoo's condition codes.
Well, if you got a better idea (which i bet there is) be free to suggest.
My thought is to return the matching value from a set of arrays, but not shure how to do it.
My code now looks like this:
function getCondition(code) {
var snow = [1, 2, 3],
sun = [4, 5, 6];
}
What i need is the variable name that contains the matching number of the code?
I've made a JS-Fiddle
http://jsfiddle.net/BH8r6/
The fastest lookup (translating a Yahoo code to your label) is to use the code as array key (if they are sequential).
var weather = [];
weather[0] = "no_weather";
weather[1] = "snow";
weather[2] = "snow";
weather[3] = "snow";
weather[4] = "sun";
weather[5] = "sun";
weather[6] = "sun";
function getCondition(code) {
return weather[code];
}
Why dont you try an associative array when your key is your variable name and your values is the corresponding code for the variable name, thus your code will be something like this:
var myCodeArray=[];
myCodeArray["snow"]=[1, 2, 3];
myCodeArray["sun"] = [4, 5, 6];
now your method getCondition will be
function getCondition(code)
{
for(var definedCodeName in myCodeArray)
{
if(myCodeArray.hasOwnProperty(definedCodeName))
{
var array=myCodeArray[definedCodeName ];
for(var i=0;i<array.length;i++)
{
if(array[i]==code){
return definedCodeName ;}
}
}
}
return "Not found";
}
Demo
Why to complicate everything?! Just use 'switch' :
function getCondition(code) {
switch( code ){
case 1:
case 2:
case 4:
case 6:
return "snow";
case 3:
case 8:
case 9:
return "sun";
case 5:
case 7:
case 10:
return "cloudy";
}
return "none";
}

unique values in array count

I have an array like the following
var data = [
["1"," 101_30.1.101_34","0.0200112629","mm/s","[OK]"],
["1"," 101_30.1.101_35","0.0146548533","mm/s","[OK]"],
["1"," 101_30.1.101_45","0.0146548533","mm/s","[OK]"],
["1"," 101_42.2.101_43","0.0101406257","mm/s","[OK]"],
["2"," 102_17.3.102_38","5.1719756","mm/s","[WA]"],
["2"," 102_17.3.102_39","3.5886707","mm/s","[WA]"],
["2"," 102_17.3.102_44","9.4615074E-4","mm/s","[OK]"],
["2"," 102_40.4.102_41","4.8159785","mm/s","[OK]"],
["3"," 204_15","3.8374166","mA","[OK]"],
["4"," 501_11","1027.5156","RPM","[WA]"]
]
What im trying to do is find how many unique array there are. Example 1=4,2=4,3=1,4=1
The data is coming from a database, so the number of arrays can always change.
Here is a simple jsfiddle of what im talking about JsFiddle
Try something like this:
var count = {};
$.each(data, function(){
var num = this[0]; // Get number
count[num] = count[num]+1 || 1; // Increment counter for each value
});
console.log(count); // {1: 4, 2: 4, 3: 1, 4: 1}

Categories