Open In App

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 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: 

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




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()




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.




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: 

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.




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.




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.




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.




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.




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.


Article Tags :