Array utility functions : A real utility

If you cannot answer the following questions then this post if for you

  • 1. Array.prototype.some === [].some // true or false?
  • 2. There are 5000 names in an array. I want to check if any name is empty. Will it be good to use for loop?
  • 3. There is an array of select options for e.g. [{id: ‘1’, text: ‘First option’},…]. I want to remove those entries which have empty text. Which utility function can I use?
  • 4. Server returns an array of names. I want to create an array of select options in format {id, text}. Which utility function should I use?
  • 5. Have you ever used map or reduce utility functions?

Arrays are pretty fundamental to any programming language. In traditional languages we need to clearly define what kind of data an array can hold. But Javascript arrays are totally different and also behave in a completely different way.

In JS, array can hold anything irrespective of datatype. For e.g. [‘1′, 123, {key:’value’}, [1,2,3], null, undefined] is a valid array in JS. If we do a length check on this, it will return 6. This makes arrays too much powerful for those who do not care about the type of data. But too weak for those who come from traditional programming languages like Java.

For everyday use Javascript provides you with several utility functions so that you don’t have to write a loop every time you encounter an array. Creating a for loop involves creating new variables in function scope which can result in overriding existing variables and also introduces overhead of maintaining such variables. The utility functions helps getting rid of all these problems.

The first function that I use the most is ‘some’. From MDN

“The some() method tests whether at least one element in the array passes the test implemented by the provided function.”

The good thing here is that the test itself can be a function and thus you can have a function defined at a common place and can reuse it at other places too. For solving the question #2 we would typically write a loop like this.

var names = ['Peter','Mona','','',....]; // a list of 5000 names
var anyNameEmpty = false;
for(var i=0; i<names.length; i++){
if(names[i] == ''){
anyNameEmpty = true;
break; // we dont want to test for other remaining elements as our condition has already met
}
}

With the utility function ‘some’, the whole code above can be re-written as

var anyNameEmpty = names.some(function(element){ return element=='';}); // You can also get rid of anyNameEmpty variable for more concise code

Basically, internally “some” function also does the same kind of thing. It iterates over all the values of array and runs the function passed as argument and returns true if any iteration results in true. By using the “some” function you also guarantee that you will get either true or false. While having a custom for loop can result in inadvertent values. Also you dont need to set the start and end index. Its all managed internally.

Using these utility functions gives you enough power to control everything you need. The parameters for these kind of utility functions are almost similar.

Parameters explanation picked up from MDN directly.

callback
Function to test for each element, taking three arguments:

currentValue
The current element being processed in the array.
index Optional
The index of the current element being processed in the array.
array Optional
The array some() was called upon.

thisArg Optional
Value to use as this when executing callback.

To answer question #3, we can use another common function “filter” like below

selectOptions.filter(function(item){ return item.text;});

As you can see, using javscript’s coercion and filter function we saved a lot of boilerplate code. In fact in ES6 arrow functions make this a whole lot simpler. In ES6 you can write the same as

selectOptions.filter(item => item.text);

To answer question#4 we have another popular utility function “map”. Its task is to iterate over each element and map every element to a callback and return a new array with same number of elements.

For eg. server returns data such as [{id:1, name:’Pola’,age:24, image:’user.png’},{id:2, name:’Cola’,age:29, image:’user.png’},{id:3, name:’Lola’,age:24, image:’user.png’},{id:4, name:’Sola’,age:24, image:’user.png’}]. We want to construct a select options dropdown from this array. Use map function as below

names.map(function(item){return {id: item.id, text: item.name};}) // returns a new array with elements having only id and text.

Another common utility function is ‘reduce’. Reduce is a generic term and means go over every element to determine a single value. For eg you want to calculate the sum of values in an array [2,4,5,6,77,88]. Instead of creating a for loop and a new variable we can use ‘reduce’ link below.

values.reduce(function(sum, item){ return sum + item;}, 0) // Calculate sum with sum set to 0 initially

These are some of the utility functions which are already present in Javascript(ES5 and above). One thing to note is that these are also commonly available while using jQuery, lodash etc type of libraries. The nomenclature might differ a little. For eg Underscore has reject instead of filter function.

Surely the above information would be more helpful once you start using these in your day to day coding.

Leave a Reply

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