Javascript Assessment: Arrays

I’m working my way through Rebecca Murphey’s javascript assessment tests, so I thought I’d write a brief summary of the test problems and resolutions as I go through them.

Arrays Test 1: You should be able to determine the location of an item in an array.

My first answer was to use an array’s indexOf() method, which is called on the array you want to search and takes the element you want to find as it’s only required parameter. It returns the first element that is a strict match and if it doesn’t find a match, it returns -1. Optionally, you can send a second parameter with the index of where you want to start the search (if that number is negative, the offset is from the end of the array although it still searches from beginning to end).


function(arr, item) {
  return arr.indexOf(item);
}

This method is an extension to the ECMA-262 standard and is not implemented in several versions of IE including IE8, but you can extend the array.prototype.indexOf() functionality in your code.

Another option is to iterate over the array with a for loop and check if there is a strict match against the item. If not, return -1.


for (var i = 0, len = arr.length; i < len; i++) {
  if (arr[i] === item) {
    return i;
  }
}
return -1;

A third option is to use the jQuery inArray() method.


if ($.inArray("item", arr) != -1) {
  return;
}

I believe that usually in javascript we’re only doing things a few times and the readability of jQuery outweighs the performance benefits of using a native method, which tend to perform faster. That would depend on the size of the array though.

Further reading:

Arrays Test 2: You should be able to add the values of an array.

You can use the native reduce method, which calls a function on each element in the array from left to right and reduces it to a single value. You can optionally provide it with an initial value or it’ll just use the first element in the array. This is another example of a method that won’t work in all browsers, but you can extend the Array.prototype.reduce() functionality if you need to support those browsers.


array.reduce(function(a,b) {
    return a+b;
}

You can also just use a for loop that iterates through the array and assigns the new sum to a variable.


var total = 0;
for (var i = 0,  len = array.length; i < len; i++) {
    total += someArray[i] << 0;
}

Further reading:

Arrays Test 3: You should be able to remove a value from an array.

One way to return a value from an array is to iterate through the array, checking to see if each item is the one you want to remove. Add each item to a new array unless it is the one you want to remove and then return the new array.


var ret = [];

for (var i = 0, len = arr.length; i < len; i++) {
  if (arr[i] !== item) {
    ret.push(arr[i]);
  }
}

return ret;

Arrays Test 4: You should be able to remove a value from an array, returning the original array.

The last test didn’t actually remove an item from an array; it simply copied the array to a new array without the specified item. To remove an item from the original array, you can use the splice method. The splice method changes the content of an array, taking an index as an argument telling it where to start changing the array. You can also send an optional argument telling it how many old array items to remove.


var i, len;

for (i=0, len = arr.length; i < len; i++) {
  if (arr[i] === item) {
    arr.splice(i, 1);
    i = i - 1;
    len = len - 1;
  }
}

return arr;

Further reading:

Arrays Test 5: You should be able to add an item to the end of an array.

You can add items to the end of an array using the push method, which simply adds the passed in item to the end of the array and returns the new array length. To pass this test, you just use the push method on the array, and then return the array.


function (arr, item) {
  arr.push(item);
  return arr;
};

Further reading:

Arrays Test 6: You should be able to remove the last item of an array.

Further reading:

To remove the last item of an array, you can use the pop method which returns the removed item. To pass the test, you just use the method on the array and return the array.


function(arr) {
  arr.pop();
  return arr;
}

Arrays Test 7: You should be able to add an item to the beginning of an array.

You can use the unshift method on an array to add an item to the beginning of the array. Like the push method, it returns the new length of the array, so to pass the test you need to return the array.


function (arr, item) {
  arr.unshift(item);
  return arr;
};

Further reading:

Arrays Test 8: You should be able to remove the first item of an array.

You can use the shift method on an array to remove the first item. Like the pop method, it returns the item removed, so to pass the test you need to return the array.


function (arr) {
  arr.shift();
  return arr;
};

Further reading:

Arrays Test 9: You should be able to join together two arrays.

You can call the concat method on an array, passing in another array. This will return a new array comprised of the elements from the array that it was called on and the elements of the array that were passed to it while leaving the first two arrays unchanged. To pass this test, just return the resulting array.


function(arr1, arr2) {
  return arr1.concat(arr2);
}

Further reading:

Array Test 10: You should be able to add an item anywhere in an array.

You can use the splice method on an array to insert an item anywhere in the array. The splice method requires two arguments and takes an optional third. The first argument is the index position where you want to start removing items and the second argument is the number of items you want to remove. The third optional argument is what you’d like to add to that location. So to insert an item anywhere in the array, you pass in the index, set the number to remove to 0, and then pass in the element you want to add. Splice returns the removed elements, so to pass the test, you want to return the array.


function(arr, item, index) {
  arr.splice(index, 0, item);
  return arr;
}

Further reading:

Array Test 11: You should be able to count the occurences of an item in an array.

You can find the number of times an item appears in an array by creating a count variable that starts at 0. Then, loop through the array and check it current element against the item that you are counting. Every time there is a match, increment the count by one.


function(arr, item) {
  var count = 0;
  for (i=0, len = arr.length; i < len; i++) {
    if (arr[i] === item) {
      count++;
    }
}
return count;

Array Test 12: You should be able to find duplicates in an array.


  var seen = {};
  var duplicates = [];

  for (var i = 0, len = arr.length; i < len; i++) {
    seen[arr[i]] = seen[arr[i]] ? seen[arr[i]] + 1 : 1;
  }

  for (var item in seen) {
    if (seen.hasOwnProperty(item) && seen[item] > 1) {
      duplicates.push(item);
    }
  }

  return duplicates;

Further reading:

Arrays Test 13: You should be able to square each number in an array.


  var squared = [];
  for (var i = 0, len = arr.length; i < len; i++) {
    squared.push(arr[i]*arr[i]);
  }
  return squared;

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>