What are the differences between the built in traversal methods of JS array

  • 2021-12-04 09:15:58
  • OfStack

Directory forEach () (ES6) Method map () (ES6) Method flatMap () Method for... in... for...of... filter (ES6) iterates through the array every () function (ES6) find () Function (ES6) findIndex () Function (ES6)

forEach () (ES6) Method

The forEach () (ES6) method executes the given function once on each element of the array.

1. If there are several elements in the array, the callback in this method will be executed several times
2. The first parameter is the element in the array, the second parameter is the index of the element in the array, and the third parameter is itself (the third parameter can be used to deduplicate the array)
3. With the traversal method of array, foreach is more efficient than for when the number of cycles is unknown or the calculation is complicated
4. Loop's array element is the basic data type, does not change the original data's data, the loop's array element is the object, will change the original array's object attribute value
5. The index modification is not supported in the loop process, and the use of return in callback will not report an error, but it is invalid

Note: If you can't use break and continue to jump out of the whole loop or the current loop, you will report an error, but you can jump out of the loop with try... catch


const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));

Disadvantages: There is no way to stop or jump out of the ` forEach () ` loop

map () (ES6) Method

The map () (ES6) method creates a new array, and the result is that each element in the array is the return value after calling the supplied function once.


    const array1 = [1, 4, 9, 16];
    const map1 = array1.map(x => x * 2);
    console.log(map1);  //[2, 8, 18, 32]

3 parameters: array element, element index, original array itself

flatMap () method

The flatMap () method first maps each element using a mapping function, and then compresses the result into a new array. It is almost identical to flat with depth value 1 attached to map, but flatMap is usually slightly more efficient in merging into one method.


    var arr1 = [1, 2, [3, 4]];
    arr1.flatMap(x => x);    //[1, 2, 3, 4]
    var arr1 = [1, 2, 3, 4];
    arr1.flatMap(x => [[x * 2]]);   // [[2], [4], [6], [8]]

for...in...

This loop uses a lot of people, but it is the least efficient (the output key is an array index). If the traversal is an object, the output is the attribute name of the object

for...of...

Better performance than ` for... in... ` but still not as good as the normal ` for 'loop
Note: Objects cannot be looped, because any data structure can complete traversal operation as long as Iterator interface is deployed. Some data structures have Iterator interface natively, such as Array, Map, Set, String, etc., while Iterator interface is deployed on Symbol. iterator attribute of data structure, while Object object just does not have Symbol. iterator attribute, so it cannot be traversed by for.. of

filter (ES6) Traverses Array

filter (ES6) iterates through the array, filters out the eligible elements and returns a new array, or an empty array if none of the array elements pass the test.


    const result = words.filter(word => word.length > 6);
    console.log(result)   //["exuberant", "destruction", "present"]
some () function ( ES6 ) 
     Traverses the array to see if there are any eligible elements, and the return value is Boolean Value 
     This, as long as it finds it 1 If you meet the requirements, you will return  true . 
    var arr = [
     { id: 1, name: ' Buy a pen ', done: true },
     { id: 2, name: ' Buy a notebook ', done: true },
     { id: 3, name: ' Practice calligraphy ', done: false }
    ]
    
    var bool = arr.some(function (item, index) {
     return item.done
    })
    console.log(bool)    // true

every () Function (ES6)

Test whether each element of the array passes the test of callback function
If all pass, return true, otherwise return false
Simply put, if the callback function returns true each time, every () returns true, otherwise it is false.


    var arr = [
        { id: 1, name: ' Buy a pen ', done: true },
        { id: 2, name: ' Buy a notebook ', done: true },
        { id: 3, name: ' Practice calligraphy ', done: false }
    ]
    var bool = arr.every((item, index) => {
        return item.done
    })
    console.log(bool)    // false

find () Function (ES6)

Returns the first element that passes the test, or **undefined** if no element passes the test.


    var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
    var num = arr.find( (item, index) => {
        return item === 3
    })
    console.log(num)   //  3

findIndex () Function (ES6)

This function works the same way as find () above, except that it returns the index of the first element.


    var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
    var num = arr.findIndex(item => {
        return item === 3
    })
    console.log(num)   //  4

Related articles: