JavaScript – Common Array operations

Below are a few common operations one might come across. I’ve used Array.map() and Array.forEach() at times which requires JavaScript 1.6 or higher, but I’m not sure if older versions of Internet Explorer would support them. You might have to use a regular for loop there or use a library like Dojo, etc.

To check if an element exists in a 2-D array – Needle in a Haystack


function findNeedle(num) {
  var arr = [[2, 3, 5], [6, 8, 9], [14, 16, 19], [44, 66, 67]];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i][0] > num) {
      return (arr[i - 1] ? arr[i - 1].indexOf(num) > -1 : false);
    }
  }
}

console.log(findNeedle(8)); // this one is faster because it just looks at the first element of each array.

function findNeedle2(num) {
  var arr = [[2, 3, 5], [6, 8, 9], [14, 16, 19], [44, 66, 67]];
  var flattenedArr = arr.map(function(item) {
    return item.join();
  });

  return flattenedArr.join().indexOf(num) > -1;
}

console.log(findNeedle2(3));  //this one constructs a big string out of the whole array and then does an indexOf on it.

To check if 2 arrays are equal:

function checkIfEqual(arr1, arr2) {
  if (arr1.length != arr2.length) {
    return false;
  }
  //sort them first, then join them and just compare the strings
  return arr1.sort().join() == arr2.sort().join();
}
var arr1 = [2, 3, 5, 6];
var arr2 = [5, 6, 2, 3];

checkIfEqual(arr1, arr2);

To convert an arguments object in a function to an Array, do this:

function add() {
 return [].slice.call(arguments); // note that Array.prototype.slice.call works as well, but [].slice is concise and cool
}

console.log(add(2,3,5));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s