Thursday, February 23, 2017

Iterating through an array with a function


var array = ['apple','banana','grapefruit','cantelope'];

// Backwards
function reportarray(array) {
  var max = array.length;
  console.log(array[max - 1]);
  array.pop();
  if(max > 1) {
    return (reportarray(array));
  } else {
    return -1;
  }
}

// Forwards
function reportarrayrev(array) {
  var max = array.length;
  console.log(array[0]);
  array.shift();
  if(max > 1) {
    return (reportarrayrev(array));
  } else {
    return -1;
  }
}

// Except this is destructive and destroys the array
// Now for a non-desctructive way

var array = ['apple','banana','grapefruit','cantelope'];

// Backwards
function reportarray(array) {
  var arraynew = array.slice(0);
  var max = arraynew.length;
  console.log(arraynew[max - 1]);
  arraynew.pop();
  if(max > 1) {
    return (reportarray(arraynew));
  } else {
    return -1;
  }
}

// Forwards
function reportarrayrev(array) {
  var arraynew = array.slice(0);
  var max = array.length;
  console.log(arraynew[0]);
  arraynew.shift();
  if(max > 1) {
    return (reportarrayrev(arraynew));
  } else {
    return -1;
  }
}


// Thanks for the slice comment: https://davidwalsh.name/javascript-clone-array

No comments:

Post a Comment