Joined July 2015
·

Jeff Cheung

i code and get interrupted constantly
·
Naperville
·
·
·

Posted to Remove Element (JS Algorithm) over 1 year ago

Your first function returns the length of the array, so I'm not quite sure if that's what you intended; however, here is a way without a loop.

var int = 3;
var arr = [3,3,3,3,3];
function removeElement(int, arr) {
  if(typeof int != 'number' && typeof arr != 'object') {
    return false;
  }
  // build a regexp that will account for commas on either side of the searched number so we can join it and replace all instances of the number
    var pattern = new RegExp(int.toString() + "|," + int.toString() + "|" + int.toString() + ",", "g");
    arr = arr.join().replace(pattern, "").split(",");
  if (arr.join() == "")
  {
  // this is to account for an array with just one element of an empty string
      return new Array();
  }
  else
  {
  // return the array that is split
      return arr;
  }
}

alert(removeElement(int, arr).length);
Posted to Vowel Count (JS Algorithm) over 1 year ago

you don't need to regexp.match each character. regexp.match returns all the matches in the array, and you can get the length of the array once without a for loop.

function vowel_count(str)
{
  'use strict';

  if(typeof str != 'string') {
    return false;
  }

  var count = 0;
  var pattern = /[aeiou]/ig;
  var matches = str.match(pattern);
  return matches != null? matches.length:0;
}
Achievements
1 Karma
0 Total ProTip Views