IFE JS Exercises (2 | 3) Array sort,forEach,slice and filter methods

Keywords: Javascript

Code block:

var aqiData = [
    ["Beijing", 90],
    ["Shanghai", 50],
    ["Fuzhou", 10],
    ["Guangzhou", 50],
    ["Chengdu", 90],
    ["Xi'an", 100]
];

/*
    Write the code under the comment
    Traversing to read the data of each city in aqiData
    Display cities with air quality index greater than 60 in the aqi-list list
*/
         
var aqiUl = document.getElementById('aqi-list');
    var city = aqiData.filter(function (a) {   //The parameter a equals aqiData[a]
        return a[1] > 60;                 //Judging that the number in the array is greater than 60
    });
    city.sort(function (a,b) {
        return b[1] - a[1];
    });
    (function write(){
        city.forEach(function(v,i,a) { //The parameter is a callback function. The callback function has three parameters: the current element, the element index, and the entire array.
        var li = document.createElement('li');
        aqiUl.append(li);
        li.innerHTML = "The first" + (i + 1) + "name" + v[0] + "," + v[1];
    });
})();

Solving problems

1. Using filter method to obtain cities with air quality greater than 60
2. Sorting cities with air quality greater than 60 by using sort method
3. Use the forEach method to traverse array elements into innerHTML appended to <ul>.

Summary of Solving Problem Thoughts

1. Using filter method to obtain cities with air quality greater than 60
//Do not use filter method
var city = [];
for(var i = 0; i < aqiData.length; i++){
    if(aqiData[i][1] > 60){
        city.push(aqiData[i][1]);
    }
}

//Using filter method
var city = aqiData.filter(function (a) {   
//The parameter a equals aqiData[i], the value of the current element
    return a[1] > 60;                 
    //The filter calls back once for each element of the array to determine that the number in the array is greater than 60
});

Array.prototype.filter()

The filter tests all elements with the specified function and creates a new array containing all elements that pass the test.

Syntax: var new_array = arr.filter(callback[, thisArg])

parameter

callback
Functions used to test each element of an array. The parameters (element, index, array) are used when invoking.
Returning true means that the element is retained (tested), while false does not.
thisArg
Optional. The value used for this when calling back is executed.
Return value
An array of a new set of tested elements

describe

filter calls the callback function once for each element in the array, and creates a new array with all the elements that make the callback return true or the value equivalent to true. Callback will only be invoked on indexes that have been assigned, but will not be invoked on indexes that have been deleted or have never been assigned. Elements that fail the callback test are skipped and not included in the new array.

When callback is called, three parameters are passed in
1. Value of elements
2. Index of elements
3. Traversed arrays
Such as:

//The parameter a equals aqiData[i], the value of the current element
//The parameter b equals i, and the index of the current element (subscript)
//The parameter c equals aqiData, the whole array
var city = aqiData.filter(function (a,i,v) {   
    return a[1] > 60;                 
    console.log(a[1]) //90,50,10,50,90,100
    console.log(aqiData[i][1]) //90,50,10,50,90,100
    console.log(v[i][1])  //90,50,10,50,90,100
});

If you provide a thisArg parameter for the filter, it will be used as the this value when the callback is called. Otherwise, this value of callback will be global in non-strict mode and undefined in strict mode.

2. Sorting cities with air quality greater than 60 by using sort method
//Do not use the sort method
function swap(arr,index1,index2){
    var temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;
}

var arr = city,i,j;
//Bubble sort
for(j = 0; j < arr.length; j++){
    for(i = 0; i < arr.length - j; i++){
        if(arr[i] > arr[i+1]){
            swap(arr,i,i+1);
        }
    }
}

//Using the sort method
city.sort(function (a,b) {
    return b[1] - a[1];
});

Array.prototype.sort()

The sort() method sorts the elements of the array at the appropriate location and returns the array. Sort sort sort is not necessarily stable. The default sort order is based on the string Unicode code code points.

Grammar: arr. sort () arr. sort (compareFunction)

describe

If a - b is in ascending order [1, 2, 3]
If b - a is in descending order [3, 2, 2]

city.sort(function (a,b) {
    return b[1] - a[1]  // 100,90,90
    return a[1] - b[1]  //90,100,100
});
3. Use the forEach method to traverse array elements into innerHTML appended to <ul>.
(function write(){
    //The parameter is a callback function. The callback function has three parameters: the current element, the element index, and the entire array.
        city.forEach(function(v,i,a) { 
        var li = document.createElement('li');
        aqiUl.append(li);
        li.innerHTML = "The first" + (i + 1) + "name" + v[0] + "," + v[1];
    });
})();

Syntax:

array.forEach(callback(currentValue, index, array){
    //do something
}, this)
array.forEach(callback[, thisArg])

parameter

callback
A function that is executed for each element in an array and receives three parameters:

  • CurrtValue (current value)
    The current element being processed in the array.

  • Index
    Index of the current element being processed in the array.

  • array
    The array that the forEach() method is operating on.

This Arg is optional
Optional parameters. When the callback function is executed, it is used as the value of this (reference object).

//At this point city is filtered and sorted.
//The parameter is a callback function. The callback function has three parameters: the current element, the element index, and the entire array.
//Parameter a equals city[i], the value of the current element
//The parameter b equals i, and the index of the current element (subscript)
//Parameter c equals city, the whole array
city.forEach(function(v,i,a) { 
    var li = document.createElement('li');
    aqiUl.append(li);
    li.innerHTML = "The first" + (i + 1) + "name" + v[0] + "," + v[1];
    console.log(v[1]) //100,90,90
    console.log(city[i][1]) //100,90,90
    console.log(a[i][1])  //100,90,90
});

Getting two-dimensional arrays

Here's a section of HTML. How do you get it and store it in a two-dimensional array?

<!--
The array format is as follows:
data = [
       ["Beijing", 90],
       ["Beijing", 90]
       ……
       ]  
-->
<ul id="source">
    <li>Beijing Air Quality:<b>90</b></li>
    <li>Air quality in Shanghai:<b>70</b></li>
    <li>Tianjin Air Quality:<b>80</b></li>
    <li>Air quality in Guangzhou:<b>50</b></li>
    <li>Air quality in Shenzhen:<b>40</b></li>
    <li>Fuzhou Air Quality:<b>32</b></li>
    <li>Air quality in Chengdu:<b>90</b></li>
</ul>

1. First, we create a one-dimensional array and get all the li
2. By traversing all li through the for loop and storing the cities and air in each li in a new array, we will implement this by slice() method.

var source = document.getElementById('source').getElementsByTagName('li');
var data = new Array();  //Create a one-dimensional array
for(var i = 0; i < source.length; i++){
    var data[i] = new Array(); //This is a two-dimensional array.
    //Here the first two characters in li are intercepted and stored in an array by slice
    //Because innerHTML is string type, slice is used to cut strings.
    data[i][0] = source[i].innerHTML.slice(0,2);    
    //GetElements ByTagName ('b') is an array, so take [0], and convert it to a numerical type with Number.
    data[i][1] = Number(source[i].getElementsByTagName('b')[0].innerHTML);
        
}

Conclusion:

filter method for array filtering
sort method for array sorting
forEach method for array traversal
slice method for interception
Number Method Converts Number Classes

Posted by nadeemshafi9 on Thu, 20 Dec 2018 08:36:05 -0800