Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have been trying to create a table dynamically based on an array return from another function.
I have 2 array :
var listOfNames = ['a', 'b', 'c'];
var scoreLabels = ['Query', 'Entry', '% Matched', 'Alignment Len', 'Mismatches', 'Gaps', 'E-Value', 'Bitscore'];
The first array will contain element which will be id of each row.
The second array is the list of columns for each row.
My html looks like this
<table>
<tbody></tbody>
</table>
and the for loop that I have written looks like this :
for (var i = 0; listOfNames.length < i; i++) {
var row = $('<tr></tr>');
$(row).attr('id', listOfNames[i]);
for (var x = 0; scoreLabels.length < x; x++) {
var tableHeader = $('<td></td>');
$(tableHeader).attr('text', scoreLabels[x]);
$(tableHeader).appendTo(row);
}
$(row).appendTo('table');
}
I have been looking at other posts that teaches the creation of table dynamically with jquery, but to no avail.
Please kindly advice and let me know where i went wrong .
The js fiddle can be found here
http://jsfiddle.net/t16scofy/2
For-loops...
Just read your for-loops out loud:
for (var i = 0; listOfNames.length < i; i++) {...}
becomes:
for i - starting at 0 - do ... as long as the length of listOfNames is smaller then i.
I starts at 0. and the length of listOfNames is always larger then 0. It is never smaller. so this for loop will never do ...
Same goes for you inner for-loop
corrected:
for (var i = 0; i < listOfNames.length; i++) {...}
or if you really want the i after the .length:
for (var i = 0; listOfNames.length > i; i++) {...}
You have a few typos and wrong conditions in both your for loops.
This should do it:
var listOfNames = ['a', 'b', 'c'];
var scoreLabels = ['Query', 'Entry', '% Matched', 'Alignment Len', 'Mismatches', 'Gaps', 'E-Value', 'Bitscore'];
// If i starts with 0, and you're incrementing it, you obviously want the loop
// to go until it reaches a bigger value, not the other way round.
for (var i = 0; i < listOfNames.length; i++) {
var row = $('<tr>', { class: i.toString() });
// If x starts with 0, and you're incrementing it, you obviously want the loop
// to go until it reaches a bigger value, not the other way round.
for (var x = 0; x < scoreLabels.length; x++) {
var tableHeader = $('<td>', { text: scoreLabels[x] });
tableHeader.appendTo(row);
}
row.appendTo('table');
}
Demo
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am facing a problem with javascript problem-solving.
I am now trying to print out the smallest name from a named array. But I cannot print out it. It shows the different names. Would you mind helping me, please?
see the codes.
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 0; i < tinyFriend.length; i++) {
var char = tinyFriend[i];
if (char < tiny) {
tiny = char;
}
}
console.log(tiny);
please tell me where to make the correction
Just use the Reduce Method
var tinyFriend = ['hasan' , 'md' , 'mdhasan' , 'zahdhasan'];
var tiny = tinyFriend.reduce(function(a, b) {
return a.length <= b.length ? a : b;
});
console.log(tiny)
use the inbuilt sort method
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend.sort((a, b) => a.length - b.length)[0];
console.log(tiny);
fix for original code
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 0; i < tinyFriend.length; i++) {
var char = tinyFriend[i];
if (char.length < tiny.length) { // use length
tiny = char;
}
}
console.log(tiny);
You can simply use for-of loop here to get the smallest string in an array
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
let smallest;
for (let word of tinyFriend) {
if (smallest !== undefined) smallest = word.length < smallest.length ? word : smallest;
else smallest = word;
}
console.log(smallest);
You are making mistake in these two lines for (var i = 0; i <tinyFriend.length; i++) { & if (char < tiny) {
You have assigned tinyFriend[0]; to tiny so no need to start loop from 0. Instead start from 1. Secondly here if (char < tiny) { you need to check length
Here is my solution. Inside the loop just check if the length of the current name is smaller than the previous, then assign that name to tiny
var tinyFriend = ["hasan", "md", "mdhasan", "zahdhasan"];
var tiny = tinyFriend[0];
for (var i = 1; i < tinyFriend.length; i++) {
tiny = tiny.length > tinyFriend[i].length ? tinyFriend[i] : tiny;
}
console.log(tiny);
I am trying to run a replace text function on my slides based on an two arrays; the first array is the values that are to be replaced and the second array are the values that the corresponding values in the first array should be replaced with.
I.e. the first value in the first array should be replaced by the first value in the second array.
This is my attempt at doing it
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value2','new value 3'];
for (i = 0, s = 0, x = 0; i < currentPresentationSlide.length, s < array1.length, x < array2.length; i++, s++, x++) {
currentPresentationSlide[i].replaceAllText(array1[s],array2[x])
}
}
What further complicates it is, that the replaceAllText will only run on a single page and not the entire presentation, hence it will have to be run as a loop on each individual page in the slide (which is the reason for the loop with the i variable.
Does anyone know what I am doing wrong, cause this is not working for me
Thanks to Rup in the comments i solved it. Just in case anyone has the same issue this is my solution:
function myFunction() {
var currentPresentationSlide = SlidesApp.getActivePresentation().getSlides();
var array1 = ['{{remove}}','{{remove2}}','{{remove3}}'];
var array2 = ['new value','new value 2','new value 3'];
for (i = 0; i < currentPresentationSlide.length; i++) {
for (s = 0; s < array1.length; s++)
currentPresentationSlide[i].replaceAllText(array1[s],array2[s])
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I calculate a "Top-5-List" of Birthplaces organized in an array of objects in this form
var myObjArr =[
{
"birth":
{
"year": 2012,
"name": "Manchester, Vermont, USA",
}
} , (and so on)
];
My approach however does not seem to be much performant:
for (var i = 0; i < myObjArr.length; i++) {
var alreadyListed = -1;
for (var j = 0; j < resultData.length; j++) {
if(resultData[j].key == myObjArr[i]['birth']['name']) { // birthname already in resultData
alreadyListed = j;
break;
}
}
if(alreadyListed != -1 ) { // birthname already in resultData -> raise count
resultData[alreadyListed].count += 1;
}else { // birthname not yet in resultData -> add to resultData
resultData.push({key: myObjArr[i]['birth']['name'], count: 1 });
}
}
}
Neiter javascript's forEach nor angulars angular.forEach seem to improve the performance. Any Suggestions?
You can use an object as a dictionary instead of using an array and looking for a key by iterating, this way the second "loop" is done by the Javascript implementation when looking for object keys (also it's probably not a linear scan but an hash table lookup):
var result = {};
myObjArr.forEach(function(obj) {
var key = "!" + obj.birth.name;
result[key] = 1 + (result[key] || 0);
});
I'm always adding a "!" in front of the key when using objects as dictionaries because all Javascript objects do have an inherited constructor property and I don't want to interfer with that.
The (x || 0) trick is to start with a 0 when a name has not seen before (undefined is falsy in Javascript). Adding 1 to undefined instead results in NaN.
If you really need an array as result the code is only slightly more complex:
var result = [];
var index = {};
myObjArr.forEach(function(obj) {
var key = "!" + obj.birth.name;
var ix = index[key];
if (ix === undefined) {
// Allocate a new entry
index[key] = result.length;
result.push({key:key, count:1});
} else {
result[ix].count += 1;
}
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a small script that should detect duplicate elements in an array of fields on a form.
function dupes() {
var unique = [];
//Loop through array of fields to get entered values
for (i = 0; i <= 9; i++) {
unique[i] = Number(document.getElementById('proj' + i).value);
}
unique.sort();
//Now compare the array values. If there are any duplicates, throw an error
for (i = 1; i <= 9; i++) {
if (unique[i] == unique[i - 1]) {
document.getElementById('errormsg').innerHTML = 'duplicated values!';
return false;
}
}
}
There are ten of these "proj" fields (proj0 - proj9), and I have an onClick event assigned to call this function. If there are any duplicate values, the span 'errormsg' is supposed to display an error, but it's not working. What might I be missing?
//Check for duplicate project numbers
function errorCheck() {
var unique = [];
//Loop through array of fields to get entered values
for (i = 0; i <= 9; i++) {
var currentValue = Number(document.getElementById('projNo' + i).value);
if(unique.indexOf(currentValue)!=-1)
{
document.getElementById('projError').innerHTML = 'duplicated values!';
return false;
}
unique[i]=currentValue;
}
return true;
}
FiddleDEMO
It first checks whether a value is already in the array by using unique.indexOf(currentValue). This function returns the index of the searched element and returns -1 if it is not found.
If it was not found, it adds it to the array and goes to the next one.
Edit:
If you want to reset the error message when you submit again and there are no more duplicates, don't forget to reset it before return true; like so:
document.getElementById('projError').innerHTML = 'no duplicates ;)';
This will detect the duplicate values :
var arr= [];
//Loop through array of fields to get entered values
for (i = 0; i <= 9; i++) {
arr.push(Number(document.getElementById('proj' + i).value));
}
function dupes(arr) { // pass the array to find dupes
var i, len=arr.length, unique= [], obj={};
for (i=0;i<len;i++) {
obj[arr[i]]=0;
}
for (i in obj) {
unique.push(i);
}
if(unique.length != arr.length) {
document.getElementById('errormsg').innerHTML = 'duplicated values!';
}
}
dupes(arr);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am trying to find a math based way to find a password that makes the if statement in the below code true. I have written some stuff that brutes its way to an answer but that does not help me to understand how to solve this problem mathematically. The actual password I need to make the if statement true is irrelevant and not what I am asking for. I specifically want some code to get me started or even complete code that I can study to show me how to reverse engineer this algorithm to arrive at the answer using JavaScript.
var passed = false;
function checkPass(password) {
var total = 0;
var charlist = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < password.length; i++) {
var countone = password.charAt(i);
var counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
if (total == 248410397744610) {
passed = true;
alert(password);
}
}
Here's a simple code snippet that will do it:
function invertPass(n) {
var all = 'abcdefghijklmnopqrstuvwxyz',
out = '',
offset;
while (n > 0) {
offset = n % 17;
out = all.charAt(offset - 1) + out;
n = (n - offset) / 17;
}
return out;
}
function createPass(password) {
var total = 0;
var charlist = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < password.length; i++) {
var countone = password.charAt(i);
var counttwo = (charlist.indexOf(countone));
counttwo++;
total *= 17;
total += counttwo;
}
return total;
}
var orig = 'gdclhpdhbied',
num = createPass(orig);
console.log(invertPass(num) === orig);
Take a look at what the function actually does to total depending on its input: It multiplies by 17 and adds the position of the current char in the alphabet.
Therefore your expectedTotal (e.g. 248410397744610) will be a number divisible by 17 plus the alphabet position of the password's last letter. Use % (the modulus operator) to find said position (simply put, the number you need to subtract from expectedTotal to make it divisible by 17), then divide by 17 and repeat.