Must use JavaScript Array Functions – Part 3
Last Updated :
20 Jun, 2023
Previous articles:
In this article, we are going to discuss the following JavaScript array functions
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']
Similar Reads
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS)
DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers
NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers
HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network
A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read