A few tips on how to work better with Arrays in JS

Array

If you're like me who always end up using for loop to do any operation involving arrays, you should probably have a look below at some "hidden" methods available in ECMAScript5 (the current version on Javascript) to work with Arrays.

I say "hidden" because these functions I'm going to show you are available for a while in most of the browsers but most of the people haven't heard about them or haven't used them yet.

Below are some functions ordered by how frequent I'm likely to use them.

forEach - Iterates through every item in the array and do whatever you need with each item.

['C', 'D', 'E'].forEach(function(element, index) {
  console.log(element + " is the #" + (index+1) + " in musical scale");
});

// Output
// C is the #1 in musical scale
// D is the #2 in musical scale
// E is the #3 in musical scale

map - It creates a new array with the result of the callback function. This method is good to be used when you need to format the elements of your array.

// Let's upper case the items in the array
['bob', 'joe', 'jen'].map(function(elem) {
  return elem.toUpperCase();
});

// Output: ['BOB', 'JOE', 'JEN']

reduce - As the name says it reduces the array to a single value by calling the given function passing in the currenct element and the result of the previous execution.

[1,2,3,4].reduce(function(previous, current) {
  return previous + current;
});

// Output: 10
// 1st iteration: previous=1, current=2 => result=3
// 2nd iteration: previous=3, current=3 => result=6
// 3rd iteration: previous=6, current=4 => result=10

every - Returns true or false if all the elements in the array pass the test in the callback function.

// Check if everybody has 18 years old of more.
var ages = [30, 43, 18, 5];  
ages.every(function(elem) {  
  return elem >= 18;
});

// Output: false

filter - Very similar to every except that filter return an array with the elements that return true to the given function.

// Finding the even numbers
[1,2,3,4,5,6].filter(function(elem){
  return (elem % 2 == 0)
});

// Output: [2,4,6]

Conclusion

Although they're handy, one downside of using these methods above is that they may not be available in some old browsers, this might be one of the reasons they didn't catch on.

In case you need to support IE8 for example, I'd suggest you taking a look at Lo-Dash utility library, which provides all of the features listed above and also support older browsers.

Get access to free Chapters of my eBook The Basis of Unit Testing

I'll never share your email address or spam you.

comments powered by Disqus