I am wondering what`s the problem with this simple code. I am making a function where I need to get the length of the shortest word in a string. I know that I can find this function anywhere but,
why mine isn't working?
function findShort(s){
var arr = s.split(" ");
var out = 1000;
for (var i = 0; i < arr.length-1; i++){
if (arr[i] <= out){
out = arr[i].length;
}
}
return out;
}
The above function returns 1000 instead.
You need to compare the length of each word (arr[i].length), not each word itself (arr[i]) to the shortest length so far.
function findShort(s){
var arr = s.split(" ");
var out = 1000;
for (var i = 0; i < arr.length-1; i++){
if (arr[i].length <= out){ // <-- here!
out = arr[i].length;
}
}
return out;
}
Your problem is that when you compare strings in javascript, it doesn't use it's length. You have to use the "length" attribute of a String, like in the fixed code below. Also you have to save the result to give an output
function findShort(s){
var arr = s.split(" ");
var comp = 1000;
var out = "";
for (var i = 0; i < arr.length-1; i++){
if (arr[i].length <= comp){
comp = arr[i].length;
out = arr[i];
}
}
return out;
}
There still is a problem, if you want to have an array returned with all the shortest words (same length). You could add another if statement and make it add the word to an array when it's the same length, and clear it when there was found a shorter one.
I have a function that takes an input of a string and a single char that will count how many times that char appears in that string.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++)
if (str.charAt(i) == letter)
num += 1;
return num;
}
console.log(count("BBC", "B"));
//output 2
It works fine like this, but this took me some time to figure out. Its second hand nature for me to always put brackets on a for loop but when i do that, the function doesn't work as i anticipated it would, like so:
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter)
num += 1;
return num;
}
}
console.log(count("BBC", "B"));
//outputs 1
Why are the brackets causing it to act this way?
Why are the brackets causing it to act this way?
Because you have the return statement inside of the for loop block. At the end of the block, the function returns.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) { // block start
if (str.charAt(i) == letter)
num += 1;
return num; // exit function in first loop
} // block end
}
It's not the braces (brackets are []), it's the placement of the return statement. The return statement is in the first iteration of the loop (i = 0). If you add an extra set of braces (as seen below), it becomes more obvious.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
num += 1;
}
return num; // <-- This return exits the function
}
}
console.log(count("BBC", "B"));
//outputs 1
In the First one return statement was outside for loop, but in the second one return statement is inside the for loop. That made the difference.
Try the below code.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter)
num += 1;
}
return num;
}
console.log(count("BBC", "B"));
your loop gets terminated after first iteration.
So if you try to get the occurrence of "B" in "XBBBB...B" it will return 0.
Try to debug your code and place brackets at right position.
Learn to debug your js code using browser.
I'm running a 'for' loop to check if the elements in the winOptions array are in the oneNums array. However, every time I use indexOf property it sends back -1 even if the number is in the oneNums array. Is it possible it returns that because ['1','2'] is different that [1,2]? How can I fix this.
I have this variables:
var oneNums = [];
var winOptions = [[1,2,3],[4,5,6],[7,8,9],[1,5,9],[3,5,9],[1,4,7],[2,5,8],[3,6,9]];
var a;
And this jQuery function:
$('.btn-xo').click(function(){
if (turn === 'one'){
$(this).text(pickOne);
$(this).prop('disabled', true);
oneNums.push($(this).val());
oneNums.sort(function(a, b){
return a - b;
});
for(var i = 0; i < winOptions.length; i++){
for(var j = 0; j < winOptions[i].length; j++){
a = oneNums.indexOf(winOptions[i][j]);
if (a === -1){
p1 = [];
break;
} else {
p1.push(oneNums[a]);
console.log('aca');
}
}
}
console.log(a);
turn = 'two';
count += 1;
}
indexOf string with number will fail. So, change number to string
First convert number to String, using .toString()
for(var i = 0; i < winOptions.length; i++){
for(var j = 0; j < winOptions[i].length; j++){
a = oneNums.indexOf((winOptions[i][j]).toString());
if (a === -1){
p1 = [];
break;
} else {
p1.push(oneNums[a]);
console.log('aca');
}
}
}
Check these two examples,
['1','2'].indexOf(1); o/p ===> -1
['1','2'].indexOf((1).toString()); o/p ===> 0
It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey
I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);