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.
Related
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(",")
}
I have cart system for a website I made. I'm currently trying to create a discount deal in the checkout page. I've put together an if statement but its not quite working. see below:
for (var i in cartArray) {
if((cartArray[i].name=="Shampoo") &&
(cartArray[i].name=="Drinks Can") &&
(cartArray[i].name=="Small Brush"))
{
console.log("yes");
} else {
console.log("no");
}
}
I get '5 no' in the console but when I use the OR operator it works. But that won't do as I need the code to recognize all 3 simultaneously so I can proceed further with the discount. Thank you in advance.
ps. heres what the console looks like in full:
(5) [{…}, {…}, {…}, {…}, {…}]
0: {name: "500ml Conditioner", price: 1.5, count: 1, total: "1.50"}
1: {name: "1.5L Bleach", price: 2.5, count: 1, total: "2.50"}
2: {name: "Small Brush", price: 2.5, count: 1, total: "2.50"}
3: {name: "Shampoo", price: 4, count: 1, total: "4.00"}
4: {name: "Drinks Can", price: 1, count: 1, total: "1.00"}
You want to check item names as you iterate through your cart. Right now, though, you're checking all three possible names against the same item (cartArray[i].name) on each pass. So your code will never return 'yes' because the same item can never have three different names.
One way to fix this might be to use three booleans that start false and get set to true when a name matches. For example:
var shampoo = false;
var drinks = false;
var brush = false;
for (var i in cartArray) {
switch (cartArray[i].name) {
case "Shampoo":
shampoo = true;
break;
case "Drinks Can":
drinks = true;
break;
case "Small Brush":
brush = true;
break;
}
if (shampoo && drinks && brush) {
console.log("yes");
break;
}
}
if (!shampoo || !drinks || !brush) {
console.log("no");
}
Instead of testing on every loop, you could also test only when a boolean is set true, checking whether the other two are already true. You could also use if ... else if ... if you prefer it to switch. Plenty of ways to accomplish what you want.
Well i'm not sure what you are trying to achieve but your current statement ask for the i-th item of the cart array to be named Shampoo, Drinks Can and Small Brush at the same time with the AND operator. Either use a switch statement for your purpose or consequent if-s. You could do something like:
for (var i in cartArray)
{
switch cartArray[i]:
case "Shampoo":
// do what you need
break;
case "Drinks Can"
// do something
break;
default: console.log("no")
}
Read about switch statement here
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;
});
As you can see in the image below, I have some returned json data with three objects; each contains a clients id => data.
exact_match : {104}
match_4 : {104, 103}
match_2 : {104, 103, 68}
How can I "trim" or remove the duplicate objects based on previous ones? something like:
exact_match : {104}
match_4 : {103}
match_2 : {68}
I tried _.difference but did not work (Maybe because it is for arrays not objects?):
var exact_match = data.exact_match,
match_four_digits = _.difference(data.match_4, data.exact_match),
match_two_digits = _.difference(data.match_2, data.exact_match, data.match_4),
Any help would be appreciated :)
Update
I need that the returned value has the same object data instead of a new array :)
It looks like you want to diff keys (or rather, it'd be efficient to — _.keys)
_.difference(
_.keys({104: 1, 102: 3, 101: 0}), // ["104", "102", "101"]
_.keys({104: 1, 102: 3}) // ["104", "102"]
)
// [ "101" ]
Or, you could always convert your object to an array of pairs if you want to compare within the objects too (_.pairs):
_.difference(
_.pairs({104: 1, 102: 3, 101: 0}), // [["104",1], ["102",3], ["101",0]]
_.pairs({104: 1, 102: 2}) // [["104",1], ["102",2]]
)
// [["102", 3], ["101", 0]]
I would create a map called unique, e.g. var unique = {}; and then iterate over each key in your data and check if it's in unique. If it is in unique, delete the entry associated with that key, thus removing duplicates.
You could pull this check out as an alreadyFound method:
var alreadyFound = function (key) {
if (!(key in unique)) {
unique[key] = true;
return false;
}
return true;
};
Then iterate over your data and check alreadyFound(key) for key in your data, and delete the key if alreadyFound(key) returns true.
You could go messing with lodash/underscore methods but those might be inefficient depending on how you use them (and how they're implemented) and this should operate in linear time.
It looks like for your specific use case the full solution would be something like:
var unique = {};
// Assume I copy and pasted alreadyFound here
var alreadyFound = ...;
for (var object in data) {
// Iterate through ids in each object in data
for (var id in object) {
// Remove this entry if it's already found
if (alreadyFound(id)) {
delete object[id];
}
}
}
Thanks guys for the answers, I really appreciate your time.
I searched further and found this post by Lodash developer that helped me came up with this snippet;
var data = {
exact_match: {
104: {
supplier_id: 104
}
},
match_four_digits: {
104: {
supplier_id: 104
},
68: {
supplier_id: 68
}
},
match_two_digits: {
104: {
supplier_id: 104
},
68: {
supplier_id: 68
},
103: {
supplier_id: 103
},
999: {
supplier_id: 999
}
}
};
var arr_match_four_digits = _.difference(_.keys(data.match_four_digits), _.keys(data.exact_match));
var arr_match_two_digits = _.difference(_.keys(data.match_two_digits), _.keys(data.match_four_digits), _.keys(data.exact_match));
$('#output1').html(JSON.stringify(data));
$('#output2').html(JSON.stringify(_.pick(data.match_four_digits, arr_match_four_digits)));
$('#output3').html(JSON.stringify(_.pick(data.match_two_digits, arr_match_two_digits)));
<script src="https://cdn.rawgit.com/lodash/lodash/3.3.1/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
data
<pre><code><div id="output1"></div></code></pre>
arr_match_four_digits
<pre><code><div id="output2"></div></code></pre>
match_two_digits
<pre><code><div id="output3"></div></code></pre>
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";
}