Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Array join() Function
Next article icon

Must use JavaScript Array Functions – Part 3

Last Updated : 20 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Previous articles: 

  • 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

  • prototype.reduce()
  • prototype.concat()
  • prototype.sort()
  • prototype.reverse()

JavaScript Array.Prototype.reduce(): 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 the array from left to right. The value returned by the callback function is available to the next element as an argument to its callback function. In case the initialValue is not provided, reduce’s callback function is directly called on the 2nd element with the 1st element being passed as previousValue. In case the array is empty and the 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 the callback function is invoked for the first time. 

Example 1: To find the sum of an array of integers.

Javascript




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

Output:

15

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

Javascript




let 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;
}
 
let totalSalesInNY = arr.reduce(reduceFun2);
 
console.log(totalSalesInNY.sales);
 
 

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 the callback function, the variable previousValue has to have an integer value and not the whole object. If we don’t pass the initialValue as 0, then for the first iteration, the previous value will become the whole object and will try to add an integer value to it, thereby giving junk output.

Array.prototype.concat(): 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.

 Below are some examples showing the use of Array.prototype.concat():

Example 1: In this example, we will concatenate two arrays. 

Javascript




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

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Example 2: In this example, we will concatenate three arrays.

Javascript




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

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Array.prototype.sort(): 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 of 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. 

Below are some examples showing the use of Array.prototype.sort():

Example 1: In this example, we will sort a simple integer array. 

Javascript




let arr = [3, 1, 5, 4, 2].sort();
console.log(arr);
 
 

Output:

[1, 2, 3, 4, 5]

Example 2: In this example, we will sort a simple string array. 

Javascript




let arr = ["Orange", "Apple", "Banana"].sort();
console.log(arr);
 
 

Output:

['Apple','Banana','Orange']

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

Syntax:

array.reverse()

Parameters: Not Applicable 

Below are some examples showing the use of Array.prototype.reverse():

Example 1: In this example, we will reverse an array with integer values using the Array.prototype.reverse() method.

Javascript




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

Example 2: In this example, we will reverse an array with string values using the Array.prototype.reverse() method.

Javascript




let arr = ['Javascript', 'HTML', 'CSS'];
arr.reverse();
console.log(arr);
 
 

Output:

['CSS', 'HTML', 'Javascript']


Next Article
JavaScript Array join() Function
author
kartik
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javaScript
  • javascript-array
  • Web technologies

Similar Reads

  • Most useful JavaScript Array Functions – Part 1
    In this article, we are going to discuss the following two JavaScript array functions. Both of these functions are widely used in industry and make the JavaScript code clean, modularized, and easy to understand. Array.prototype.every()Array.prototype.some()Array.prototype.every(): This function is u
    6 min read
  • Most useful JavaScript Array Functions – Part 2
    In Most useful 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 loo
    7 min read
  • Array of functions in JavaScript
    Given an array containing functions and the task is to access its element in different ways using JavaScript. Approach: Declare an array of functions.The array of functions works with indexes like an array function. Example 1: In this example, the function call is initiated from the element of the a
    2 min read
  • JavaScript Array join() Function
    The JavaScript Array.join() method is used to join the elements of the array together into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ). Syntax: Array.join([separator]) Parameters: [separator]: A string to separate each element
    2 min read
  • JavaScript Return multiple values from function
    To return multiple values from a function, you can pack the return values as elements of an array or as properties of an object. This approach allows functions to efficiently produce and deliver diverse sets of values, enhancing flexibility and versatility in JavaScript programming. Below are the ap
    2 min read
  • JavaScript Array find() function
    JavaScript arr.find() function is used to find the first element from the array that satisfies the condition implemented by a function. If more than one element satisfies the condition then the first element satisfying the condition is returned. Syntax: arr.find(function(element, index, array), this
    3 min read
  • JavaScript Function Parameters
    Function parameters are variables defined in the function declaration that receive values (arguments) when the function is called. They play a key role in making functions reusable and dynamic. Values are assigned to parameters in the order they are passed.You can assign default values to parameters
    2 min read
  • Map to Array in JavaScript
    In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
    3 min read
  • How to write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 min read
  • Reverse an Array in JavaScript
    Here are the different methods to reverse an array in JavaScript 1. Using the reverse() MethodJavaScript provides a built-in array method called reverse() that reverses the elements of the array in place. This method mutates the original array and returns the reversed array. [GFGTABS] JavaScript let
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences