Most useful JavaScript Array Functions – Part 2
Last Updated :
04 Aug, 2023
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 look at 2 array methods that modify the array and return the modified array.
Array.Prototype.filter(): It is used to get a new array that has only those array elements which pass the test implemented by the callback function. It accepts a callback function as an 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:
array.filter(callback(element, index, arr), thisValue)
Parameters: This function accepts five parameters as mentioned above and described below:
- callback: This parameter holds the function to be called for each element of the array.
- element: The parameter holds the value of the elements being processed currently.
- index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
- array: This parameter is optional, it holds the complete array on which Array.every is called.
- thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Examples: Filter out the students who got more than 80 percent marks.
Example 1: Function to filter out the students who got more than 80 percent marks. It is a naive Method using loop
JavaScript
function fnFilterStudents_loop(aStudent) {
let tempArr = [];
for (let 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));
Output:
[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];
Example 2: Here we will be using Array.prototype.filter()
JavaScript
function fnFilterStudents_filter(aStudent) {
return aStudent.filter(function (oStudent) {
return oStudent.fPercentage > 80.0;
});
}
aStudent = [
{ sStudentId: "001", fPercentage: 91.2 },
{ sStudentId: "002", fPercentage: 78.7 },
{ sStudentId: "003", fPercentage: 62.9 },
{ sStudentId: "004", fPercentage: 81.4 }];
console.log(fnFilterStudents_filter(aStudent));
Output:
[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];
Example: To remove undefined elements from an array
Example: Function to remove undefined elements from an array. In the callback function of the below example, we are returning elements directly. So if the element has value, it will be treated as true and if the element is undefined, it will be automatically treated as false.
JavaScript
function removeUndefined(myArray) {
return myArray.filter(
function (element, index, array) {
return element;
});
}
let arr = [1, undefined, 3, undefined, 5];
console.log(arr);
console.log(removeUndefined(arr));
Output:
[1,undefined,3,undefined,5];
[1,3,5];
Array.Prototype.map(): It 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 the callback function is called on indexes of elements that have assigned values including undefined.
Syntax:
array.map(callback(element, index, arr), thisValue)
Parameters: This function accepts five parameters as mentioned above and described below:
- callback: This parameter holds the function to be called for each element of the array.
- element: The parameter holds the value of the elements being processed currently.
- index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
- array: This parameter is optional, it holds the complete array on which Array.every is called.
- thisArg: This parameter is optional, it holds the context to be passed as this is to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Examples: A scenario where the user has to reduce each amount in an array by a specific tax value
Example 1: Function to add property bIsDistinction to each object in the array, using Loop.
JavaScript
function fnAddDistinction_loop(aStudent) {
for (let 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));
Output:
[{sStudentId : "001" , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : "002" , fPercentage : 78.7 , bIsDistiction : true},
{sStudentId : "003" , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : "004" , fPercentage : 81.4 , bIsDistiction : true}];
Example 2: Here we will be using Array.prototype.map() function.
JavaScript
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));
Output:
[
{sStudentId : "001" , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : "002" , fPercentage : 78.7 , bIsDistiction : true},
{sStudentId : "003" , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : "004" , fPercentage : 81.4 , bIsDistiction : true}];
Example: A scenario where the user has to create a new property of every object in an existing array of objects.
Example: Array.prototype.Map() is used with standard JavaScript functions. For example, with the Math.sqrt() function to calculate the square root of each element in an array or to parse string values to float.
JavaScript
console.log([1, 4, 9].map(Math.sqrt));
console.log(["1.232", "9.345", "3.2345"].map(parseFloat))
Output:
1,2,3
1.1099,3.0569,1.7984
One has to be careful while using Array.prototype.map() with standard functions because something like this can happen.
JavaScript
console.log(["1", "2", "3"].map(parseInt));
Output:
1,NaN,NaN
Why did the above code snippet return, NaN? This happened because the 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 the first iteration, the index being 0 is passed as radix to parseInt which defaults it to 10 and thus you see the first element parsed successfully. After that, it gets messed up.
Below is the fix for the above mess up.
JavaScript
console.log(["1", "2", "3"].map(function (val) { return parseInt(val, 10) }))
Output:
1,2,3
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 checking against array length, and then incrementing the counter variable. Keeping these things in mind is not only a hassle but also makes code prone to bugs. For example, a developer might accidentally misspell “array.length” as “array.length”. 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 that can come to the rescue which has an equivalent utility function.
Must use JavaScript Array Functions -Part 3
This article is contributed by Harshit Jain
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.
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
Must use JavaScript Array Functions â Part 3
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(): Ar
5 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
Dense and Sparse Array in JavaScript
In JavaScript, an array is a data structure used for storing a collection of values. Each value in the collection is assigned a unique index number. Arrays in JavaScript can contain values of any data type, such as strings, numbers, objects, and even other arrays. In JavaScript, arrays can be of two
7 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
Types of Arrays in JavaScript
A JavaScript array is a collection of multiple values at different memory blocks but with the same name. The values stored in an array can be accessed by specifying the indexes inside the square brackets starting from 0 and going to the array length - 1([0]...[n-1]). A JavaScript array can be classi
3 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 use push() & pop() Methods in JavaScript Arrays?
Arrays are dynamic data structures in JavaScript that have the ability to hold several values of various types. The push() and pop() methods are used for adding and removing elements from an array's last index.1. Using push() Method in JavaScriptThe push() method is used to add or push the new value
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