ES6 map, filter, find, find index

Keywords: React less Javascript IE

The new project uses a lot of es6 grammar in react. I've seen Mr. Ruan Yifeng's introduction to es6 once before. Recently, I found that there are many places that I don't understand very deeply. So I've come again. By the way, I'll summarize some very practical methods.
First of all, I declare that this article is reproduced: original link =>. https://www.cnblogs.com/studyshufei/p/7910384.html
The blogger wrote very well, so he got it, and kept it for review in the future! uuuuuuuuuuu

map method: can be simply understood as mapping

var arr=[1,2,3,4];
console.log( arr.map((n)=>n*n) );//[1, 4, 9, 16]
console.log( arr.map((n)=>n-1) );//[0, 1, 2, 3]

Find me a number less than 0 from the array [1, 4, - 5, 10]. When you see this, I believe you also know about the arrow function, (n) => n * n.

filter method:

var users = [
  {name: "Baby Zhang", "email": "zhang@email.com"},
  {name: "Jiang Yiyan",   "email": "jiang@email.com"},
  {name: "Li Xiaolu",  "email": "li@email.com"}
];
//Acquiring all email
var emails=users.map(user=>user.email) 
console.log(emails.join(',')) //"zhang@email.com", "jiang@email.com", "li@email.com"
//Get the email of the designated person
var liEmail=emails.filter(email=>/^li/.test(email))
console.log(liEmail.join('')) //li@email.com

Get all the users'email in the user list, map helps us to do this. The map method passes a parameter, which represents each item in users. The map obtains the email of each user item by traversing all user items, then push es it to an array, and returns it to us as a value. Secondly, we need to get the email of the designated person. The filter method comes on the stage. The filter filters the email as an array and returns the result to us. The filter method here is the email that matches regularly to the beginning of li, and then returns.

find method:

[1, 4, -5, 10].find((n) => n < 0)    // -5

The find method understands better. The parameter n here represents every item in the array. Then the find method finds the item < 0 (- 5) by traversing every item in the array.

findIndex method: The callback function of find method can accept three parameters, which are the current value, the current position and the original array. Look at an example:

[1, 4, -5, 10].findIndex((value,index,arr) => value < 0)  // 2

In this example, value represents each item of the array, 1, 4, - 5, 10. Index represents the index value of each item, arr represents the array [1, 4, - 5, 10], and then we need to return the index value of the item < 0, that is, 2.

The internal mechanism of these four methods has a traversal process, which is much simpler than forEach.

Then the ES6-some() and every() methods are supplemented.

    //every()
    let numbers = [2, 4, 10, 4, 8];
    let a = numbers.every((item,index)=>{
        if(item%2===0){
            return true;
        }else{
            return false;
        }
    });
    console.log(a)

    //some()
    let b=numbers.some((item,index)=>{
         if(item%3===0){
            return true;
        }else{
            return false;
        }
    })
    console.log(b)

Every () method returns true only if one of them is true. On the contrary, every () method returns true only if all of them are true, even if one of them is false. Purpose: To determine whether all members of an array satisfy the specified test. Refer specifically to MDNhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some.

To sum up:

Follow-up additions: Recently, many small partners are learning ES6, such as ES6 map, how to achieve in ES5?

/*
 * MAP Object, Implementing MAP Function
 *
 * Interface:
 * size()                     Get the number of MAP elements
 * isEmpty()                  Judging whether MAP is empty
 * clear()                    Delete all elements of the MAP
 * put(key, value)            Add elements (key, value) to the MAP 
 * remove(key)                Delete the specified KEY element, return True successfully, and False unsuccessfully
 * get(key)                   Gets the element value VALUE of the specified KEY, and fails to return NULL
 * element(index)             Gets the elements of the specified index (using element.key, element.value to get KEY and VALUE), and fails to return NULL
 * containsKey(key)           Determine whether the MAP contains elements that specify KEY
 * containsValue(value)       Determine whether the MAP contains elements that specify VALUE
 * values()                   Get all the VALUE arrays in the MAP (ARRAY)
 * keys()                     Get all KEY arrays in the MAP (ARRAY)
 *
 * Example:
 * var map = new Map();
 *
 * map.put("key", "value");
 * var val = map.get("key")
 * ……
 *
 */
function Map() {
    this.elements = new Array();

    //Get the number of MAP elements
    this.size = function() {
        return this.elements.length;
    };

    //Judging whether MAP is empty
    this.isEmpty = function() {
        return (this.elements.length < 1);
    };

    //Delete all elements of the MAP
    this.clear = function() {
        this.elements = new Array();
    };

    //Add elements (key, value) to the MAP 
    this.put = function(_key, _value) {
        this.elements.push( {
            key : _key,
            value : _value
        });
    };

    //Delete the specified KEY element, return True successfully, and False unsuccessfully
    this.removeByKey = function(_key) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };
    //Delete all elements of the specified KEY
    this.removeAllByKey=function(_key){
        for (var i = this.elements.length - 1; i >= 0; i--) {
            if (this.elements[i].key == _key) {
                this.elements.splice(i, 1);
            }
        }
    }

    //Delete the element that specifies VALUE, return True successfully, and False unsuccessfully
    this.removeByValue = function(_value) {//removeByValueAndKey
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value == _value) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };

    //Delete the element that specifies VALUE, return True successfully, and False unsuccessfully
    this.removeByValueAndKey = function(_key,_value) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value == _value && this.elements[i].key == _key) {
                    this.elements.splice(i, 1);
                    return true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };

    //Gets all the element values VALUE of the specified KEY, returns as an array, and fails to return false.
    this.get = function(_key) {
        var arr=[];
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    arr.push(this.elements[i].value)
                }
            }
            return arr;
        } catch (e) {
            return false;
        }
        return false;
    };

    //Gets the elements of the specified index (using element.key, element.value to get KEY and VALUE), and fails to return NULL
    this.element = function(_index) {
        if (_index < 0 || _index >= this.elements.length) {
            return null;
        }
        return this.elements[_index];
    };

    //Determine whether the MAP contains elements that specify KEY
    this.containsKey = function(_key) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].key == _key) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };

    //Determine whether the MAP contains elements that specify VALUE
    this.containsValue = function(_value) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value == _value) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };

    //Determine whether the MAP contains elements of the specified key,VALUE
    this.containsObj = function(_key,_value) {
        var bln = false;
        try {
            for (i = 0; i < this.elements.length; i++) {
                if (this.elements[i].value == _value && this.elements[i].key == _key) {
                    bln = true;
                }
            }
        } catch (e) {
            bln = false;
        }
        return bln;
    };

    //Get all the VALUE arrays in the MAP (ARRAY)
    this.values = function() {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].value);
        }
        return arr;
    };
    //Gets an array of all specified VALUE elements in the MAP (ARRAY)
    this.getAllByValue=function(_value){
        var arr=[];
        for (var i = this.elements.length - 1; i >= 0; i--) {
            if (this.elements[i].value == _value) {
                arr.push(this.elements[i]);
            }
        }
        return arr;   
    }

    //Gets an array of all VALUE s specified in the MAP key (ARRAY)
    this.valuesByKey = function(_key) {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            if (this.elements[i].key == _key) {
                arr.push(this.elements[i].value);
            }
        }
        return arr;
    };

    //Get all KEY arrays in the MAP (ARRAY)
    this.keys = function() {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            arr.push(this.elements[i].key);
        }
        return arr;
    };

    //Get key through value
    this.keysByValue = function(_value) {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            if(_value == this.elements[i].value){
                arr.push(this.elements[i].key);
            }
        }
        return arr;
    };

    //Get all KEY keys in the MAP (ARRAY) with the same extracted key as the de-duplicated key array in the de-duplicated array
    this.keysRemoveDuplicate = function() {
        var arr = new Array();
        for (i = 0; i < this.elements.length; i++) {
            var flag = true;
            for(var j=0;j<arr.length;j++){
                if(arr[j] == this.elements[i].key){
                    flag = false;
                    break;
                } 
            }
            if(flag){
                arr.push(this.elements[i].key);
            }
        }
        return arr;
    };
}

If you need IE compatibility, the map written with this ES5 should be no problem, understand how ES5 implements the map in ES6, naturally understand, follow-up goods continue to update other knowledge points of ES6, although I am also very dish, if you find a small partner with BUG, you must remember to leave a message to me, very grateful.

Follow-up supplements:

Comparing traditional writing with ES6 writing:

var users = [
  {name: "Baby Zhang", "email": "zhang@email.com"},
  {name: "Jiang Yiyan",   "email": "jiang@email.com"},
  {name: "Li Xiaolu",  "email": "li@email.com"}
];

function valuesByKey(_key) {
  //Define an empty array
  var arr = [];
  //Cyclic traversal users array
  for (i = 0; i < users.length; i++) {
    //As long as key The value is equal to_key Of,The corresponding values are allpushenter arr
    arr.push(users[i][_key]);
  }
  //Return to arr
  return arr;
}

var arr=users.map((user)=>user.name);
console.log(arr)//["Baby Zhang", "Jiang Yiyan", "Li Xiaolu"]
console.log(valuesByKey('name')) //["Baby Zhang", "Jiang Yiyan", "Li Xiaolu"]

Posted by Ward on Wed, 09 Jan 2019 08:33:10 -0800