Friday, June 10, 2016

Truncate a String

//My solution for this
function truncateString(str, num) {
  // Clear out that junk in your trunk
  //var newstr = '';
  if(num <= 3){
    str = str.slice(0,num) + '...';
  }
  else if(str.length > num){
    str = str.slice(0,num-3) + '...';
  }

  return str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 11);

Its quite simple but was getting stuck. Finally 

Friday, June 3, 2016

Confirm the Ending--My solution

/* var test = "He has to give me a new name";


var joinedarray = "He has to give me a new name".split(" ").join("").lastIndexOf("name");
var t = "He has to give me a new name".split(" ").join("").length - "name".length;
console.log(joinedarray);
console.log(t); */


function confirmEnding(str, target) {
  // "Never give up and good luck will find you."
  // -- Falcor
 
  var joinedarrayindex = str.split(" ").join("").lastIndexOf(target);
  var test = str.split(" ").join("").length - target.length;
   if(test == joinedarrayindex){
    return true;
   }
   else{
    return false;
   }
  //return str;
}

confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain");

Thursday, June 2, 2016

Return Largest Numbers in Arrays

Taking this step by step.

First to get the largest number in an array

function largestOfFour(arr) {
  // You can do this!
  for(i=0;i<arr.length;i++){
  var largest = 0;
  if(arr[i]>largest){
  largest = arr[i];
  }
  return largest;
  }
  return arr;
}

largestOfFour([4, 5, 1, 3]);


Second Step:

function largestOfFour(arr) {
  // You can do this!
   for(i =0 ; i <arr[i].length; i++){

//The trick is to assign the largest variable correctly.
     var largest = 0;
     for(k=0;k<4;k++){
       if(arr[i][k] > largest){
        largest = arr[i][k];
       }
     }
    console.log(largest);
   }
  return arr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);


Finally


function largestOfFour(arr) {
  // You can do this!
   var newarray = [];

  for (var i = 0; i < arr.length; i++){

     var largest = [];
     for(k=0;k<4;k++){
       if(arr[i][k] > largest){
        largest = arr[i][k];
       }
     }
     newarray[i] = largest;
     }
 return newarray;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);