Ads Top

Javascript Basics: Array Helper Functions - What Are They And When To Use Them

As a Javascript developer, sometimes it feels like a good portion of your time is spent working with arrays. Creating them, consuming them, appending to them, and so many other types of interactions.

Developers spend so much time with arrays that there have been libraries created to help you deal with them. Libraries such as Lodash and underscorejs come with a vast amount of helpers to make dealing with arrays (and objects) easier.

Ever since the release of ES5 and especially ES6 and forward, Javascript has added great native support that makes dealing with arrays much easier.

For now, I want to focus on the Iteration methods.

** An iteration method is a method that can be used to traverse of an array and perform different operations.

An example of iterating over an array in javascript that a lot of people might be used to seeing is the plain for loop.
for(var i = 0; i < 10; i++) {
  console.log(i);
}
This code simply sets a counter variable to 0, and prints the value each cycle through, adding 1 each time, and completing at 9 since we say when i < 10 to break out (this is implied by the second argument).

While this seems simple enough, there is a bit of code and relatively a lot to keep track of for something so trivial. There are many iteration methods. These include:
  • forEach()
  • map()
  • filter()
  • find()
  • reduce()
  • keys()
  • some()
  • reduceRight()
For this piece, lets only look at the first five. forEach() through reduce(), as these are some of the more common ones you will use.

forEach()

forEach() calls a function on each element in an array. You cannot break out of a forEach in the same way you can use break to end a for loop.

forEach() Code Example
/* Get the sum of the values of the array numbers */
var numbers = [1,2,3,4,5];

// Create a variable to hold the sum
var sum = 0;

// Loop over the array, incrementing the sum variable
numbers.forEach(function(number) {
    sum += number;
});

// Print the sum variable
console.log(sum);
Output : 15

map()

When you map over an array using map(), you get a new array where the elements are the result of calling a function on every element in the array.

map() Code Example
var numbers = [1,2,3];

var timesTwo = numbers.map(function(number) {
    return number * 2;
});

console.log(timesTwo);
Output : [ 2, 4, 6 ]

filter()

filter() creates a new array with all of the elements of this array for which the provided filtering function returns true.

filter() Code Example
/* Get male or female names from the array using filter */
var genderNames = [
 { name: 'Howard', gender: 'male' },
 { name: 'Lisa', gender: 'female' },
 { name: 'Ronnie', gender: 'male' },
 { name: 'Robin', gender: 'female' },
 { name: 'Gary', gender: 'male'}
];

var filterGender = genderNames.filter(function(name) {
 return name.gender === 'male';
});

console.log(filterGender);
Output :
[ { name: 'Howard', gender: 'male' },
  { name: 'Ronnie', gender: 'male' },
  { name: 'Gary', gender: 'male' } ]


find()

find() returns the found value in the array (only the first value), if an element in the array satisfies the provided testing function or undefined if not found.

find() Code Example
var users = [
 { loginName: 'Howard' },
 { loginName: 'Robin' },
 { loginName: 'Fred' },
 { loginName: 'Robin' }
];

var user = users.find(function(user){
 return user.loginName === 'Robin';
});

console.log(user);
Output : { loginName: 'Robin' }

reduce()

reduce() Applies a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

More explanation reduce() is a bit complex to look at without some further explanation.
A common use (or example) for reduce() is to get the sum of values in an array.

Take this example reduce() Code Example
var numbers = [ 2, 4, 6 ]; 
var sum = 0;

var result = numbers.reduce(function( sum, number) {
 return sum + number;
}, 0); // reduce takes an initial value 

console.log(result);
Output : 12

How do we get 12 for the output? reduce() takes two arguments. The first argument is a function. The second argument is the starting value. For this example, we are using 0. Think of that as a counter in a traditional for loop like this
var numbers = [ 2, 4, 6 ]; 
var sum = 0;


for (var i = 0; i < numbers.length; i++) {
 sum += numbers[i];
}
This returns the same result of 12.

It is also important to note from the reduce() example above, the first argument (the function), takes two arguments
sum = current value
number = previous value

The first pass through, the first argument (sum) is 0 and the second argument (number) is 2.
2 + 0 = 2

The second pass through, the first argument (sum) is the current value which is 2 while the second argument (previous) is the second number of the array which in this case is 4.

Finally, the last pass through we get a current value of 6 and the previous value is 6 (2 + 4).

This is great but using reduce can be used for more than just counting up values. The second argument for the function doesn't always have to start at 0 or be a number for that matter. It can be anything really. It can be a string, and array, even an object. Take this example. Here we can take this sentence and add each work as an element to the makeArray array.
makeArray = [];

function stringsToArray(string) {
 return string.split(" ").reduce(function(previous, char) {
  makeArray.push(char);
 }, 0);
}

stringsToArray("Add to array");
console.log(makeArray);
Output : [ 'Add', 'to', 'array' ]

Important: Something to keep in mind ....
While these functions often make code easier to follow and more readable, there are cases where performance will be slower than a traditional for loop. This, like many other programming decisions, will come down to readability vs performance. In most cases the performance issue will not be a major concern and can be considered over optimizing. With that, you potentially make your code less readable, which in its own way can cost time and money.

With that said, the majority of the time you can and should use these helper functions, but there may also be instances where the traditional for loop is a good solution as well.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete

Powered by Blogger.