Why must use JavaScript Array Functions

Originally published at https://www.geeksforgeeks.org

Why Must use JavaScript Array Functions – Part 1

In this article, we are going to discuss the following two JavaScript array functions

  1.  Array.prototype.every()
  2.  Array.prototype.some()

Both of these functions are widely used in industry and makes the Javascript code clean, modularized and easy to understand.

Array.prototype.every()

Description: Array.every() function is used when you need to validate each element of a given array. Array.every() accepts a callback function as argument which is called for each element of the array. The callback function has to return either a true or false. If all elements of the array satisfy the validation function and thus callback function returns true on all elements of the array, then Array.every() return true. Otherwise Array.every() returns false,as soon as it encounters the first element which does not satisfy the validator function.

Syntax : arr.every(callback[,thisArg])

Parameters :callback : Function to be called for each element of the array arr

currentValue: The value of the elements being processed currently

index(optional): Index of the currentValue element in the array starting from 0

array(optional): The complete array on which Array.every is called

thisArg (optional): Context to be passed as this to be used while executing the callback function.  If context is passed, it will be used as this for each invocation of callback function, otherwise undefined is used as default.

Sample Use Case:

1.To check if every element of the integer array is less than 100

2. To check if every element of the array is of a specific data type, for example String.

Examples

1 - Given an array, write a function to check if all elements of that array are less than 100 or not.

So the naïve approach is to use for loop as shown below.

function fnIsLEssThan100_loop(arr){ 
for(var i = 0 ; i < arr.length; i ++){ 
	if(arr[i] >= 100){ 
		return false; 
	} 
} 
return true; 
} 
function fnIsLEssThan100_loop([30,60,90]); 
function fnIsLEssThan100_loop([30,60,90,120]); 


true
false

Although the above implementation is easy to understand for any novice programmer but there are some un-necessary checks which the programmer has to take care about. For Example, the short circuiting mechanism i.e. the programmer has to explicitly make sure that as soon as the loop encounters the first element which fails the given condition, the loop should break and return false. Also until and unless the programmer dives deep into the logic of the code, he/she won’t be able to understand what this for loop is doing. But with the use of Array.every(), same behavior can be achieved with much clearer, intuitive and less code.

function fnIsLesThan100_Every(arr){ 
return arr.every(function(element){ 
			return(element < 100): 
		}); 
} 

fnIsLesThan100_Every([30,60,90]) 
fnIsLesThan100_Every([30,60,90,120]) 


true
false

2 - Given an array, write a function to check if all elements of that array are of a specified data type.

Again naïve approach would be to iterate over the array using for loop.

function fnCheckDatatype_loop(arr. sDatatype){ 
for(var i = 0 ; i < arr.length; i ++){ 
if(typeof(arr[i]) !== sDatatype){ 
return false; 

fnCheckDatatype_loop([“Geeks”,“for”,“Geeks”],“string”) 
fnCheckDatatype_loop([“Geeks”,4,“Geeks”],“string”) 


true
false

The above code snippet has the same loopholes as the previous example. Using arr.Every() those loopholes are taken care of again in code snippet below. Another point to note in the code snippet below is that we are passing two arguments to the array.every() function. The first one is the callback function (anonymous function in our case) and the second one is sDatatype. Because we need an external variable in each call of callback function, we pass it as a second argument as ‘this’ variable.

function fnCheckDatatype_Every(arr, sDatatype){ 
return arr.every(function(element){ 
return typeof(element) === sDatatype; 
},sDatatype); 

fnCheckDatatype_loop([“Geeks”,“for”,“Geeks”],“string”) 
fnCheckDatatype_loop([“Geeks”,4,“Geeks”],“string”) 


true
false

Array.prototype.some()

Description:The JavaScript array function Array.some() is in a way opposite of Array.every(). The Array.some() function is used when you need to check if at least one element of a given array passes the test implemented by the callback function. Array.some() accepts a callback function as argument which has to return either a true or false. The callback function is called for each element of the array until it returns true for at least one element of the array. If neither of the elements in the array pass the test of callback function, Array.some() returns false.

Syntax : Array.some(callback[,thisArg])

Parameters :callback : Function to be called for each element of the array arr

currentValue : The value of the elements being processed currently

index (optional) : Index of the currentValue element in the array starting from 0

array (optional) : The complete array on which Array.some()is called

thisArg (optional):Context to be passed as this to be used while executing the callback function.  If context is passed, it will be used as this for each invocation of callback function, otherwise undefined is used as default.

Sample Use Case:

1.To check if any element of the array greater than 100.

2. To check if any element of the array is even.

Examples

1 - Given an array, write a function to check if array contains any number greater than 100.

Naïve Approach

function fnIsGreaterThan100_loop(arr){ 
for(var i = 0 ; i < arr.length; i ++){ 
if(arr[i] > 100){ 
return true; 


return false; 

fnIsGreaterThan100_loop([30,60,90,120]); 
fnIsGreaterThan100_loop([30,60,90]); 


true
false

Using Array.some()

function fnIsGreaterThan100_some(arr){ 
return arr.some(function(element){ 
return(element . 100): 
}); 

fnIsGreaterThan100_some([30,60,90,120]); 
fnIsGreaterThan100_some([30,60,90]); 


 true
false

2 - Given an array, write a function to check if array contains any even number.

Naïve approach

function fnIsEven_loop(arr){ 
for(var i = 0 ; i < arr.length; i ++){ 
if(arr[i] % 2 === 0){ 
return true; 


return false; 

fnIsEven_loop([1,3,5]); 
fnIsEven_loop([1,3,5,6]); 


 false
true

Using Array.some()

function fnIsEven_some(arr){ 
return arr.some(function(element){ 
return(element %2 === 0): 
}); 

fnIsEven_some([1,3,5]); 
fnIsEven_some([1,3,5,6]); 


 false
true

One of the common mistake programmers do while using array functions like Array.every() and Array.some() is that they forget the return the value in the callback function. Mind it, if you don’t return any value from the callback function, null is returned which will be interpreted as false.

Also, it is important to know that these array functions were introduced in ECMAScript 5. So these functions are supported in IE9 or higher. If you need to use it for older browsers as well, then a library like underscore.js can come to your rescue which has an equivalent implementation of such functions.

Why Must use JavaScript Array Functions – Part 2

In Why Must use Javascript Array Functions – Part 1, we discussed two array functions namely Array.Prototype.Every() and Array.prototype.some(). It is important to note that both of these array functions accessed the array elements but did not modify/change the array itself. Today we are going to look at 2 array methods which modify the array and return the modified array.

Array.Prototype.filter()

Description: Array.prototype.filter() is used to get a new array which has only those array elements which pass the test implemented by the callback function. It accepts a callback function as argument. This callback function has to return a true or false. Elements for which the callback function returned true are added to the newly returned array.

Syntax:arr.filter(callback[, thisArg])

Parameters:

callback: callback function to be called for each element of the array arr

– currentValue: The value of the elements being processed currently

 index(optional): Index of the currentValue element in the array starting from 0

– array(optional): The complete array on which Array.prototype.filter() is called

thisArg: Context to be passed as this when used while executing the callback function. If no context is passed, undefined will be used as default value.

Sample use Cases:

1. Scenario where user has to remove all null values from an array.

2. Scenario where user has to filter out the array based on value of a particular property of objects in the array.

Example:

1.Function to filter out the students who got more than 80 percent marks.

Naïve Method using loop

<script> 
function fnFilterStudents_loop(aStudent){ 
var tempArr = []; 
for(var i = 0 ; i< aStudent.length; i ++){ 
if(aStudent[i].fPercentage > 80.0){ tempArr.push(aStudent[i]);} 

return tempArr; 

aStudent = [ 
{sStudentId : “001” , fPercentage : 91.2}, 
{sStudentId : “002” , fPercentage : 78.7}, 
{sStudentId : “003” , fPercentage : 62.9}, 
{sStudentId : “004” , fPercentage : 81.4}]; 

console.log(fnFilterStudents_loop(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : “001” , fPercentage : 91.2},
{sStudentId : “004” , fPercentage : 81.4}];

Using Array.prototype.filter()

<script> 
function fnFilterStudents_filter(aStudent){ 
return aStudent.filter(function(oStudent){ 
return oStudent.fPercentage > 80.0 ? true : false; 

	});&nbsp;
}&nbsp;
aStudent = [&nbsp;
	{sStudentId : "001" , fPercentage : 91.2},&nbsp;
	{sStudentId : "002" , fPercentage : 78.7},&nbsp;
	{sStudentId : "003" , fPercentage : 62.9},&nbsp;
	{sStudentId : "004" , fPercentage : 81.4}];&nbsp;
	
console.log(fnFilterStudents_filter(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : “001” , fPercentage : 91.2},
{sStudentId : “004” , fPercentage : 81.4}];

2. Function to remove undefined elements from an array

<script> 
function removeUndefined(myArray){ 
return myArray.filter(function(element, index, array){ 
return element; 
}); 

var arr = [1,undefined,3,undefined,5];&nbsp;

console.log(arr);&nbsp;

console.log( removeUndefined(arr));&nbsp;

</script> 

Output:

[1,undefined,3,undefined,5];
[1,3,5];

In the callback function of above example, we are returning element directly. So if the element has value, it will be treated as true and if element is undefined, it will be automatically treated as false.

Array.Prototype.map()

Description:Array.prototype.map() is used to modify each element of the array according to the callback function. Array.prototype.map() calls the callback function once for each element in the array in order. The point to note is that callback function is called on indexes of elements who has assigned value including undefined.

Syntax:arr.map(callback[, thisArg])

Parameters:

callback : Callback function to be called for each element of the array arr

– currentValue: The value of the elements being processed currently

 index(optional): Index of the currentValue element in the array starting from 0

– array(optional): The complete array on which Array.prototype.map() is called

thisArg: Context to be passed as this when used while executing the callback function. If no context is passed, undefined will be used as default value.

Sample use Cases:

1. Scenario where user has to reduce each amount in an array by a specific tax value

2. Scenario where user has to create a new property of every object in an existing array of objects.

Example:

1.Function to add property bIsDistinction to each object in the array.

Using Loop

<script> 
function fnAddDistinction_loop(aStudent){ 
for(var i = 0 ; i< aStudent.length; i ++){ 
aStudent[i].bIsDistinction = (aStudent[i].fPercentage >= 75.0) ? true : false; 

return aStudent; 

aStudent = [ 
{sStudentId : “001” , fPercentage : 91.2}, 
{sStudentId : “002” , fPercentage : 78.7}, 
{sStudentId : “003” , fPercentage : 62.9}, 
{sStudentId : “004” , fPercentage : 81.4}]; 

console.log(fnAddDistinction_loop(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : “001” , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : “002” , fPercentage : 78.7 , bIsDistiction : false},
{sStudentId : “003” , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : “004” , fPercentage : 81.4 , bIsDistiction : true}];

Using Array.prototype.map()

<script> 
function fnAddDistinction_map(aStudent){ 
return aStudent.map(function(student, index, array){ 
aStudent.bIsDistinction = (aStudent.fPercentage >= 75.0) ? true : false; 
return aStudent; 
}); 

aStudent = [ 
{sStudentId : “001” , fPercentage : 91.2}, 
{sStudentId : “002” , fPercentage : 78.7}, 
{sStudentId : “003” , fPercentage : 62.9}, 
{sStudentId : “004” , fPercentage : 81.4}]; 

console.log(fnAddDistinction_map(aStudent));&nbsp;

</script> 

Output:

[{sStudentId : “001” , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : “002” , fPercentage : 78.7 , bIsDistiction : false},
{sStudentId : “003” , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : “004” , fPercentage : 81.4 , bIsDistiction : true}];

2. Scenario where Array.prototype.Map() is used with standard JavaScript functions.

For example, with Math.sqrt to calculate square root of each element in an array or to parse string values to float.

[1,4,9].map(Math.sqrt); // Output : [1,2,3] 
[“1.232”,“9.345”,“3.2345”].map(parseFloat) // Output : [1.232, 9.345, 3.2345] 

One has to be careful while using Array.prototype.map() with standard functions because something like this can happen.

[“1”,“2”,“3”].map(parse.Int); 
//Output : [1, NaN, NaN] 

Why did the above code snippet return NaN? This happened because parseInt function accepts two arguments, First one being the element to be parsed to Integer and second as the radix which acts as base for conversion. When we use it with Array.prototype.map(), although the first argument is the element, the second argument is the index of the array element being processed currently. For first iteration, the index being 0 is passed as radix to parseInt which defaults it to 10 and thus you see first element parsed successfully. After that it gets messed up.

Below is the fix for above mess up.

[“1”,“2”,“3”].map(function(val{return parseInt(val,10)}); 
// output : [1, 2, 3] 

All code snippets used in this tutorial is available at: https://github.com/hjaintech/GeeksForGeeks/blob/master/Array_Functions_2.html

As shown in the above examples, both Array.prototype.filter() and Array.prototype.map() can be implemented using for loops. But in the above scenarios, we are trying to work on very specific use cases. Keeping a counter variable, then a checking against array length and then incrementing the counter variable. Keeping these things in mind is not only a hassle, but also make code prone to bugs. For example, developer might accidently misspell “array.length” as “array.lenght”. So as a rule of thumb, the best way to avoid programming bugs is to reduce the number of things that you are keeping track of manually. And these Array Functions do just that.

Browser support is really good for these functions but they are still not supported in IE8 or below as these array functions were introduced in ECMAScript 5. If you need to use it for older browsers as well, then you can either use es5-shim or any library like Underscore or Lodash can come to your rescue which has equivalent utility function.

Why Must use JavaScript Array Functions – Part 3

In this article, we are going to discuss the following JavaScript array functions

  1. prototype.reduce()
  2. prototype.concat()
  3. prototype.sort()
  4. prototype.reverse()

1. Array.Prototype.reduce()

Description: Array.prototype.reduce() function is used when the programmer needs to iterate over a JavaScript array and reduce it to a single value. A callback function is called for each value in array from left to right. The value returned by callback function is available to next element as an argument to its callback function. In case the initialValue is not provided, reduce’s callback function is directly called on 2nd elementwith 1st element being passed as previousValue. In case the array is empty and initial value is also not provided, a TypeError is thrown.

Syntax:

arr.reduce(callback[, initialValue])

Parameters:

callback: callback function to be called for each element of the array arr

  • previousValue: Value returned by previous function call or initial value.
  • currentValue:Value of current array element being processed
  • currentIndex:Index of the current array element being processed
  • array: The original array on which reduce is being called.

initialValue(optional): Initial value to be used as previousValue when callback function is invoked for first time.

Sample Use Cases:

1 - To find sum of an array of integers.

function reduceFun1(previousValue, currentValue, index, array){ 
return previousValue + currentValue; 

var result = [1,2,3,4,5].reduce(reduceFun1); 

console.log(result); // Output : 15 

2 - Given an array of objects containing addresses of sales locations and find the total sales done in NY   

var arr=[{name: “customer 1”, sales: 500, location: “NY”}, 
{name: “customer 1”, sales: 200, location: “NJ”}, 
{name: “customer 1”, sales: 700, location: “NY”}, 
{name: “customer 1”, sales: 200, location: “ORD”}, 
{name: “customer 1”, sales: 300, location: “NY”}]; 

function reduceFun2(previousValue, currentValue, index, array){ 
if(currentValue.location === “NY”){ 
return previousValue + currentValue.sales; 

return previousValue; 

var totalSalesInNY = arr.reduce(reduceFun2); 

console.log(totalSalesInNY); // Output: 1500 

In the above example, an initial value 0 is provided while calling the Array.reduce() on arr. In this case it is necessary to provide an initial integer value. This is because for each iteration of callback function, the variable previousValue has to have an integer value and not whole object. If we don’t pass the initialValue as 0, then for first iteration, the previous value will become the whole object and will try to add an integer value to it, thereby giving junk output.

2. Array.prototype.concat()

Description:Array.prototype.concat() is used to concatenate an array with another array/value. It does not change any existing array, instead, it returns a modified array. It accepts both new arrays and values as an argument which it concatenates with the array calling the function and returns the resultant array.

Syntax:

 NewArray = Array1.concat(value1[, value2[, …[, valueN]]])

Parameters:

valueN : New array or value to be concatenated to Array1.

Sample Use Case:

Concatenate 2 integer arrays:

var arr1 = [1,2,3,4]; 
var arr2 = [5,6,7,8]; 
var arr3 = arr1.concat(arr2); 
console.log(arr3); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

Concatenate 3 integer arrays:

var arr1 = [1,2,3,4]; 
var arr2 = [5,6]; 
var arr3 = [7,8]; 
var arr4 = arr1.concat(arr2,arr3); 
console.log(arr4); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

Concatenate an array with individual integer values:

var arr1 = [1,2,3,4]; 
var arr2 = arr1.concat(5,6,7,8); 
console.log(arr2); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

Concatenate an array with another array and other multiple values:

var arr1 = [1,2,3,4]; 
var arr2 = [5,6]; 
var arr3 = arr1.concat(arr2, 7, 8); 
console.log(arr3); // Output : [1, 2, 3, 4, 5, 6, 7, 8] 

3. Array.prototype.sort()

Description: Array.prototype.sort() is used to sort an array. It accepts an optional argument compareFunction which defines the criteria to determine which element of the array is small and which is bigger. The compareFunction accepts 2 arguments i.e. the values being compared. If value1 is smaller then compare function should return a negative value. If value2 is smaller, compareFunction should return a positive value. In case compare function is not provided, the default compareFunction converts the array elements into strings and then compares those strings in Unicode point order.

Syntax:

arr.sort([compareFunction])

Parameters:

compareFunction (optional): Function to define the sort order.

Sample Use Case:

Sort a simple integer array:

var arr = [3, 1, 5, 4, 2].sort(); 
console.log(arr); // Output : [1, 2, 3, 4, 5] 

Sort a string array:

var arr = [“Orange”, “Apple”, “Banana”].sort(); 
console.log(arr); // Output : [“Apple”, “Banana”, “Orange”] 

Sort another integer array:

var arr = [1, 30, 5].sort(); 
console.log(arr); // Output : [1, 30, 5] 

Here, the order of resultant sorted array is not correct. This is because as we are using the default sortFunction, it converts all integers into strings and then compares them based on their Unicode value. Since 30 < 5 in Unicode, Hence the incorrect sort order.

Sort the integer array using sort function:

function sortFun(a,b){ 
return a - b; 

var arr = [1, 30, 5].sort(sortFun); 
console.log(arr); // Output : [1, 5, 30] 

Here, the order is correct because we didn’t use the default sortFunction but our own sortFunction which compares the integer values to decide the sort order.

Sort an object array using sort function:

var arr = [{name:“NY”, count: 20}, 
{name:“NJ”, count: 5}, 
{name:“JFK”, count: 60}, 
{name:“ORD”, count: 1}]; 
function sortFun(obj1, obj2){ 
return obj1.count - obj2.count; 

arr.sort(sortFun); 
console.log(arr); // Output [{name:“ORD”, count: 1}, 
// {name:“NJ”, count: 5}, 
// {name:“NY”, count: 20}, 
// {name:“JFK”, count: 60}] 

4. Array.prototype.reverse()

Description: Array.prototype.reverse() is used to reverse a JavaScript array. Reverse() function modifies the calling array itself and returns a reference to the now reversed array.

Syntax:

array.reverse()

Parameters:

Not Applicable

Sample Use Case:

var arr = [1,2,3,4,5,6,7,8,9,10]; 
arr.reverse(); 
console.log(arr); //Output : [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

All code snippets used in this article are available at https://github.com/hjaintech/GeeksForGeeks/blob/master/Array_Functions_3.html

Additionally, if you wish you dive deeper into the above functions, you can refer to the following official links.

  1. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.21
  2. http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.6
  3. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11
  4. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.8

Thanks for reading

If you liked this post, please do share/like it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

JavaScript Programming Tutorial - Full JavaScript Course for Beginners

Top 10 JavaScript array methods you should know

All about JavaScript Arrays Methods


#javascript #arrays #web-development

Why must use JavaScript Array Functions
3 Likes19.20 GEEK