Skip to content
Related Articles
Open in App
Not now

Related Articles

Most useful JavaScript Array Functions – Part 2

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 15 Dec, 2022
Improve Article
Save Article

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. 

Program 1: Function to filter out the students who got more than 80 percent marks. It is a naive Method using loop

Javascript




<script>
    function fnFilterStudents_loop(aStudent){
        var tempArr = [];
        for(var 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));
</script>


Output: 

[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];

Program 2: Here we will be using Array.prototype.filter()

Javascript




<script>
    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));
</script>


Output: 

[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];

Example: To remove undefined elements from an array 

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




<script>
    function removeUndefined(myArray){
        return myArray.filter(
    function(element, index, array)
        {
            return element;
        });
    }
      
    var arr = [1,undefined,3,undefined,5];
      
    console.log(arr);
      
    console.log( removeUndefined(arr));
</script>


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 

Program 1: Function to add property bIsDistinction to each object in the array, using Loop.

Javascript




<script>
    function fnAddDistinction_loop(aStudent){
        for(var 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));
</script>


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

Program 2: Here we will be using Array.prototype.map() function.

Javascript




<script>
    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));
</script>


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.

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




<script>
    console.log([1,4,9].map(Math.sqrt));
    console.log(["1.232","9.345","3.2345"].map(parseFloat))
</script>


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




<script>
    console.log(["1","2","3"].map(parseInt))
</script>


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




<script>
    console.log(["1","2","3"].map(function(val){return parseInt(val,10)}))
</script>


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 like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!