Use an array to check data - javascript

I have an array which im using to loop through divs i have stored in variables... but i want to use the values in the array as part of the variable names i wish to check.
Heres an example of what im trying to do:
var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) { //error on this line
if(parseInt(data_+array[i]) < 3){
//do something
}
}
But i get this error Uncaught ReferenceError: data_ is not defined
Is there a way to use the array values to act like the variable name some how?

What about:
var data = [
document.getElementById('test'),
document.getElementById('test2')
];
for (var i = 0; i < data.length; i++) {
if(parseInt(data[i]) < 3){
//do something
}
}
or with an object:
var data = {
'one': document.getElementById('test'),
'two': document.getElementById('test2')
};
for (var i in data) {
if(parseInt(data[i]) < 3){
//do something
}
}

Use eval which evaluates string as javascript code
var data_a = 12;
var b = "a";
alert("data_"+b); // alerts data_a
alert(eval("data_"+b)); // alerts 12
See http://jsfiddle.net/ftGhd/

var data_one = document.getElementById('test'),
data_two = document.getElementById('test2'),
array = ['one','two'];
for (var i = 0; i < array.length; i++) {
eval("var curr_array = data_"+array[i]);
if(parseInt(curr_array) < 3){
//do something
}
}

Related

looping array of object inside for loop its only taking last condition in javascript

Trying below code but not getting expected output
I am expecting below output
[{"label":"one","value":"1","disabled":true},{"label":"two","value":"2","disabled":true},{"label":"three","value":"3","disabled":false},{"label":"four","value":"4","disabled":false},{"label":"five","value":"5","disabled":false},{"label":"six","value":"6","disabled":true}]
// ---
var A1 = [ {label:"one", value:"1"}, {label:"two", value:"2"}, {label:"six", value:"6"}];
var A2 = [ {label:"one", value:"1","disabled":false}, {label:"two", value:"2","disabled":false}, {label:"three", value:"3","disabled":false}, {label:"four", value:"4","disabled":false}, {label:"five", value:"5","disabled":false}, {label:"six", value:"6","disabled":false}];
for(let i = 0 ; i <A2.length; i++){
for(let j = 0; j < A1.length; j++){
if(A1[j].value == A2[i].value){
A2[i].disabled = true;
}
else{
A2[i].disabled = false;
}
}
}
console.log( JSON.stringify( A2 ) );
If I understand correctly what you're trying to do, the following should do it:
for(let i = 0 ; i <A2.length; i++){
A2[i].disabled = false;
for(let j = 0; j < A1.length; j++){
if(A1[j].value == A2[i].value){
A2[i].disabled = true;
break;
}
}
}
That is - start off with the false value (no match), and only set it to true if you find a match. (Then break out of the inner loop, because there's no need to continue.)
Here is an alternative perspective (jQuery option) if you want it. This is just an idea as I am sure this can be written more elegantly :)
var A1 = [ {label:"one", value:"1"}, {label:"two", value:"2"}, {label:"six", value:"6"}];
var A2 = [ {label:"one", value:"1","disabled":false}, {label:"two", value:"2","disabled":false}, {label:"three", value:"3","disabled":false}, {label:"four", value:"4","disabled":false}, {label:"five", value:"5","disabled":false}, {label:"six", value:"6","disabled":false}];
var tempA = new Array();
var resultArray = new Array();
$.each(A1,function(datakey,dataval){
tempA.push(dataval['label']);
});
$.each(A2,function(datakey,dataval){
if ($.inArray(dataval['label'],tempA)>-1) {
resultArray.push({'label':dataval['label'],'value':dataval['value'],'disabled':true})}
else {
resultArray.push({'label':dataval['label'],'value':dataval['value'],'disabled':false})
}
});
console.log(resultArray);

Compare the two array and set the value to True if value found in another array

I have two arrays
A = [1,5,9,12,14] and B = [16,4,8,12]
both the arrays have the different length. I want to compare the array A with B. If the value of array A is available in B then don't do anything else add it to sheet.
Below is my code for same but I am not getting desired output.
can anybody help me on the same?
function updateTicketsAreNotInDeploymentDoc() {
var A = getJiraNoFromJira();
var B = getJiraNoFromDoc();
for(var i = 0; i<A.length; i++) {
var data = new Array();
for(var j=0; j<B.length; j++) {
if(A[i] == B[j]) {
Logger.log("found="+A[i]);
}
}
data.push(A[i]);
}
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName(RESULTANT_DEPLOYMENT_SHEET);
sheet.appendRow(data);
}
The Sheet.appendRow() method only accept mono dimensionnal array, cause it's only add one row after the sheet. You must go through your list to append the data. As say on the documentation:
Appends a row to the spreadsheet. This operation is atomic; it
prevents issues where a user asks for the last row, and then
writes to that row, and an intervening mutation occurs between
getting the last row and writing to it.
Here is a sample of code:
Edit: As #charlietfl point it, there's is other problem before: you instanciate your data array each time you loop on your A array.
The code as being modify to correct this.
function updateTicketsAreNotInDeploymentDoc() {
var A = getJiraNoFromJira();
var B = getJiraNoFromDoc();
var data = new Array();
for(var i = 0; i<A.length; i++) {
var Found = false;
for(var j=0; j<B.length; j++) {
if(A[i] == B[j]) {
Logger.log("found="+A[i]);
Found = true;
}
}
if(Found == false){
data.push(A[i]);
}
}
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName(RESULTANT_DEPLOYMENT_SHEET);
for(var k = 0; k<data.length; k++){
sheet.appendRow([data[k]]);
}
}
Here's the quicker version, just for fun :p
The performance difference with big arrays (beyond 30k elements) is serious.
function compareArrays()
{
var obj = {};
var result = [];
var A = [1,5,9,12,14];
var B = [16,4,8,12];
for (var i = 0; i < A.length; ++i)
{
obj[A[i]] = true;
}
for (var i = 0; i < B.length; ++i)
{
if (obj[B[i]] == undefined)
{
result.push([B[i]]);
}
}
SpreadsheetApp.openById("id").getRange("A1:A" + result.length).setValues(result);
}

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

How to show a list or array into a tree structure in javascript?

I pass this list from python to javascript like this:
var string=["test_data/new_directory/ok.txt","test_data/reads_1.fq","test_data/test_ref.fa"];
I want output like this:
test_data
reads_1.fq
test_ref.fa
new_directory
ok.txt
Or also the output could be like this:
test_data
reads_1.fq
test_ref.fa
test_data/new_directory
ok.txt
I used split function to get a list with each file and directory like this:
var string=["test_data/new_directory/ok.txt","test_data/reads_1.fq","test_data/test_ref.fa"];
for(var i=0;i<string.length;i++){
var result = string[i].split('/');
console.log(result);
}
Output looks like this:
["test_data", "new_directory", "ok.txt"]
["test_data", "reads_1.fq"]
["test_data", "test_ref.fa"]
How can I convert into the format I showed above? Thanks
Sorry for being late to the party. I ran into a similar issue trying to break out a list of paths into a nested object. Here's a fiddle showing how I ended up doing it.
var list = [];
list.push("A/B/C");
list.push("A/B/D");
list.push("A/B/C");
list.push("B/D/E");
list.push("D/B/E");
list.push("A/D/C");
var data = [];
for(var i = 0 ; i< list.length; i++)
{
buildTree(list[i].split('/'),data);
}
debugger;
function buildTree(parts,treeNode) {
if(parts.length === 0)
{
return;
}
for(var i = 0 ; i < treeNode.length; i++)
{
if(parts[0] == treeNode[i].text)
{
buildTree(parts.splice(1,parts.length),treeNode[i].children);
return;
}
}
var newNode = {'text': parts[0] ,'children':[]};
treeNode.push(newNode);
buildTree(parts.splice(1,parts.length),newNode.children);
}
https://jsfiddle.net/z07q8omt/
That's certainly possible, but it requires recursion.
The first thing you'll want to do (as you've already figured out to do, in fact) is split on the slashes. We'll use map for simplicity:
paths = paths.map(function(path) { return path.split('/'); });
Now we'll want to convert this into an array of objects with name and children properties. This means we'll have to use recursion.
In this function, we'll do a first pass grouping them by their first element:
var items = [];
for(var i = 0, l = paths.length; i < l; i++) {
var path = paths[i];
var name = path[0];
var rest = path.slice(1);
var item = null;
for(var j = 0, m = items.length; j < m; j++) {
if(items[j].name === name) {
item = items[j];
break;
}
}
if(item === null) {
item = {name: name, children: []};
items.push(item);
}
if(rest.length > 0) {
item.children.push(rest);
}
}
Then we can recurse on all of these (assuming the function name we chose was structurize):
for(i = 0, l = items.length; i < l; i++) {
item = items[i];
item.children = structurize(item.children);
}
Now we've got a nice structure. We can then stringify it, again with a recursive function. Since the directory listing is just each item name followed by the indented directory contents listing, we can write that fairly easily:
function stringify(items) {
var lines = [];
for(var i = 0, l = items.length; i < l; i++) {
var item = items[i];
lines.push(item.name);
var subLines = stringify(item.children);
for(var j = 0, m = subLines.length; j < m; j++) {
lines.push(" " + subLines[j]);
}
}
return lines;
}
Then, to actually do it:
console.log(stringify(structurize(paths)).join("\n"));

Arrays Splice Pop Shift Read

I create an array like so
var membersList = $('#chatbox_members' , avacweb_chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers = [];
for(var i =0;i<membersList.length;i++){
var name = $(membersList[i]).text().replace("#","");
onlineUsers.push(name);
}
alert(onlineUsers);
listedUsers would come out something like so [Mr.EasyBB,Tonight,Tomorrow,Gone];
Question is if I use a two for loops one outside a setInterval and one inside to compare-
var membersList = $('#chatbox_members' , _chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers= [];
for(var i =0;i<membersList.length;i++){
var name = $(membersList[i]).text().replace("#","");
onlineUsers.push(name);
}
var int = setInterval(function() {
var newMember = ('#chatbox_members' , _chat.doc.body).find('li');
for(var i =0;i<newMember.length;i++){
var name = $(newMember[i]).text().replace("#","");
offLineUsers.push(name);
}
Which then would get:
onlineUsers = [Mr.EasyBB,Tonight,Tomorrow,Gone];
offLineUsers = [Mr.EasyBB,Tonight];
So to get the offline users I want to basically replace onlineUsers with offLineUsers which then should return Tomorrow,Gone . Though I know that an object doesn't have the function to replace so how would I go about this?
I don't think the splice function would work since you need to have parameters, and pop or shift are beginning and end of array.
for(var i = 0 ; i < offLineUsers.length ; i++)
{
for(var j = 0 ; j < onlineUsers.length ; j++)
{
if(onlineUsers[j] == offLineUsers[i])
{
onlineUsers.splice(j,1);
}
}
}
Try this snippet.
If I have understand well, maybe that helps:
function bus_dup() {
for(var i = 0; i < offLineUsers.length; i++) {
onLineUsers.splice(onLineUsers.indexOf(offLineUsers[i]),1);
}
offLineUsers = [];
}
This should do what you are looking for on a modern browser, using array.filter
var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];
function discord(online, offline) {
return online.filter(function (element) {
return offline.indexOf(element) === -1;
});
}
console.log(discord(onlineUsers, offLineUsers));
Output
["Tomorrow", "Gone"]
On jsfiddle
If you want the difference regardless of the order of attributes passed to the function then you could do this.
var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];
function difference(array1, array2) {
var a = array1.filter(function (element) {
return array2.indexOf(element) === -1;
});
var b = array2.filter(function (element) {
return array1.indexOf(element) === -1;
});
return a.concat(b);
}
console.log(difference(onlineUsers, offLineUsers));
console.log(difference(offLineUsers, onlineUsers));
Output
["Tomorrow", "Gone"] 
["Tomorrow", "Gone"] 
On jsfiddle

Categories