Array operation map filter

Of all the array operations, map and filter are the most useful. What these two methods can do must not fail to mention.

map
map can convert elements into arrays. As for why the array is converted, this is the beauty of map: the type is determined by the developer.
For example, the object contains numbers, but we only need numbers, the array contains functions, and Promise is needed,,,

Map can easily meet this requirement. Neither map nor filter will modify the original array, but will return a copy of the array.

    var arr1 = [{
    
     name: 0 }, {
    
     name: 1 }, {
    
     name: 2 }, {
    
     name: 3 }, {
    
     name: 4 }]
    console.log(arr1.map(x => x.name))               //[0, 1, 2, 3, 4]
    console.log(arr1.map(c => c.name * 6))            //[0, 6, 12, 18, 24]

Each element of the array will pass in three parameters when calling the provided method: the element itself, the subscript of the element, and the array itself (this is not commonly used).

    const items = ['www', 'com']
    const arrls = ['111', '222']
    const cart = items.map((x, i) => ({
    
     name: x, index: arrls[i] }))
    console.log(cart)
    // [{name: "www", index: "111"},{name: "com", index: "222"}]

filter

As the name suggests, filter is used to delete unnecessary elements in the array. Like map, it returns the deleted array.

  	var arr = [1, 2, 3, 4, 5]
    console.log(arr.filter(c => c > 3))    			// [ 4 , 5 ]
    console.log(arr.filter(c => c == 4))    		// [ 4 ]
    console.log(arr.filter(c => c < 6 && c > 4))    // [ 5 ]

So how to combine map and filter to produce good results.

    var arr = [1, 2, 3, 4, 5]
    console.log(arr.filter(c => c > 3).map(x => x*100))    // [ 400 , 500 ]
    //可能你会有疑问,为什么不直接在filter里面操作c,我们尝试一下
    console.log(arr.filter(c => (c > 3) * 100))    // [ 4 , 5 ]
    // *100 并没有生效

	//我们还可以在map中调用方法
	function C100 (c){
    
    
        return c * 100
    }
    var arr = [1, 2, 3, 4, 5]
    console.log(arr.filter(c => c > 3).map(C100) )  // [ 400 , 500 ]

Guess you like

Origin blog.csdn.net/qq_44977477/article/details/108616562