The difference between JS Array map and Array filter

Summarize:

Array.map can be understood as remapping the original array according to conditions and obtaining a new array

Array.filter can be understood as filtering the original array according to conditions and getting a new array

In other words, if you want to modify each element of the original array, then use map. If you want to delete each element of the original array according to certain rules (this deletion removes certain elements, that is, filtering), Please use filter

None of them change the native array!

Array.map

JavaScript Array map() method

The map() method returns a new array, and the elements in the array are the values ​​of the original array elements after calling the function.

The map() method processes elements sequentially in the original array element order.

It's very simple, look at the example:

var numbers = [4, 9, 16, 25];
function plusOne(num) {
    
    
    return num+1
}
numbers = numbers.map(plusOne)  
console.log('numbers: ', numbers);  //[5, 10, 17, 26]

Magical use of map: modify the object attribute name in the object array

After understanding the map above, it is not difficult to understand. In fact, it is just remapping.

Reference: https://blog.csdn.net/Wybbcc/article/details/107037225

Insert image description here

filter

Its return value is a filtered array

Insert image description here

Insert image description here

Example:

<script>

    debugger
    var ages = [32, 33, 12, 40];

    function checkAdult(age) {
    
    
        return age >= 18;
    }
	//调用checkAdult时,肯定是对数组的每个元素进行比较,
	//所以形参传入的肯定是每一个age
    let afterFilter = ages.filter(checkAdult);
    console.log(afterFilter)    //[32, 33, 40]


</script>

Rewrite the above example using arrow functions:

<script>

    debugger
    var ages = [32, 33, 12, 40];

    let afterFilter = ages.filter((age) => {
    
    
        return age >= 18;
    });
    console.log("使用箭头函数:" + afterFilter)    //[32, 33, 40]

</script>

References

Novice tutorial, w3school

Guess you like

Origin blog.csdn.net/weixin_44757863/article/details/124221168