Must use JavaScript Array Functions – Part 3

Must use JavaScript Array Functions -Part 1

Must use JavaScript Array Functions -Part 2

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.
filter_none

edit
close

play_arrow

link
brightness_4
code

function reduceFun1(previousValue, currentValue, index, array){
    return previousValue + currentValue;
}
var result = [1,2,3,4,5].reduce(reduceFun1);
          
console.log(result); // Output : 15

chevron_right


  1. Given an array of objects containing addresses of sales locations and find the total sales done in NY
filter_none

edit
close

play_arrow

link
brightness_4
code

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") {
                //console.log(previousValue.sales);
                previousValue.sales =  previousValue.sales + Number(currentValue.sales);
            }
            return previousValue;
        }
  
var totalSalesInNY = arr.reduce(reduceFun2);
  
console.log(totalSalesInNY.sales); // Output: 1500

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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]

chevron_right


Concatenate 3 integer arrays:

filter_none

edit
close

play_arrow

link
brightness_4
code

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]

chevron_right


Concatenate an array with individual integer values:

filter_none

edit
close

play_arrow

link
brightness_4
code

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]

chevron_right


Concatenate an array with another array and other multiple values:

filter_none

edit
close

play_arrow

link
brightness_4
code

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]

chevron_right


 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Sort a string array:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Sort another integer array:


filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

function sortFun(a,b){
    return a - b;
}
var arr = [1, 30, 5].sort(sortFun);
console.log(arr); // Output : [1, 5, 30]

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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}]

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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]

chevron_right


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

About the author:

“Harshit is a technology enthusiast and has keen interest in programming. He holds aharshit-jain  B.Tech. degree in Computer Science from JIIT, Noida and currently works as Front-end Developer at SAP. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5

If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks.

 



My Personal Notes arrow_drop_up

Improved By : SivaKumar22



Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.