Summary of traversal methods for javaScript arrays

Posted by brunosdiniz on Thu, 08 Aug 2019 10:18:05 +0200

Array traversal method

1.for loop

Using temporary variables, the length is cached to avoid repeated acquisition of the array length. When the array is large, the optimization effect will be more obvious.

for(var j = 0,j < arr.length;j++) {
   //Execution code
}

2.foreach cycle

Traversing through each item in the array, no return value, no impact on the original array, does not support IE

arr.forEach((item,index,array)=>{
    //Execution code
})
//Parameters: current item in value array, index of current item, array original array;
//There are several items in the array, so the anonymous callback function passed in needs to be executed several times.

3.map loops

If there is a return value, the return return value can be supported in the callback function of the returned map; what is returned is equivalent to what is the item in the array (it does not affect the original array, but is equivalent to cloning the original array, and changing the corresponding item in the cloned array)

arr.map(function(value,index,array){
  //do something
  return XXX
})
var ary = [12,23,24,42,1]; 
var res = ary.map(function (item,index,ary ) { 
    return item*10; 
}) 
console.log(res);//--> [120,230,240,420,10]; the original array was copied and modified
console.log(ary);//--> [12, 23, 24, 42, 1]; the original array has not changed

4.forof traversal

Can correctly respond to break, continue, and return statements

for (var value of myArray) {
console.log(value);
}

5.filter traversal

Do not change the original array, return the new array

var arr = [
  { id: 1, text: 'aa', done: true },
  { id: 2, text: 'bb', done: false }
]
console.log(arr.filter(item => item.done))
//Conversion to ES5
arr.filter(function (item) {
  return item.done;
});
var arr = [73,84,56, 22,100]
var newArr = arr.filter(item => item>80)   //Get a new array [84, 100]
console.log(newArr,arr)

6.every traversal

every() runs a given function for each item in an array and returns true if the function returns true for each item.

var arr = [ 1, 2, 3, 4, 5, 6 ]; 
console.log( arr.every( function( item, index, array ){ 
        return item > 3; 
    })); 
false

7.some traversal

some() runs the specified function for each item in the array, and returns true if the function returns true for any item.

var arr = [ 1, 2, 3, 4, 5, 6 ]; 
   
    console.log( arr.some( function( item, index, array ){ 
        return item > 3; 
    })); 
true

8.reduce

The reduce() method receives a function as an accumulator, and each value in the array (left to right) begins to shrink and ends up with a value.

var total = [0,1,2,3,4].reduce((a, b)=>a + b); //10

Reduc accepts a function with four parameters: the last value, the current value, the index of the current value, and the array.

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array){
 return previousValue + currentValue;
});

9.reduceRight

The function of the reduceRight() method is the same as that of the reduce(), except that the reduceRight() accumulates the array items from the end of the array forward.
When reduceRight() callbackfn is called for the first time, prevValue and curValue can be one of two values. If the initialValue parameter is provided when reducing Right () is called, prevValue equals initialValue and curValue equals the last value in the array. If no initial Value parameter is provided, prevValue equals the last value of the array and curValue equals the penultimate value of the array.

var arr = [0,1,2,3,4];
 
arr.reduceRight(function (preValue,curValue,index,array) {
    return preValue + curValue;
}); // 10

10.find

The find() method returns the first element in the array that meets the test function criteria. Otherwise return undefined

var stu = [
    {
        name: 'Zhang San',
        gender: 'male',
        age: 20
    },
    {
        name: 'Wang Xiaomao',
        gender: 'male',
        age: 20
    },
    {
        name: 'Li Si',
        gender: 'male',
        age: 20
    }
]
function getStu(element){
   return element.name == 'Li Si'
}
 
stu.find(getStu)
//The result is
//{name: `Li Si', gender: `man', age: 20}

ES6 Method

stu.find((element) => (element.name == 'Li Si'))

11.findIndex

For each element in the array, the findIndex method calls a callback function (in ascending index order) until an element returns true. As long as one element returns true, findIndex immediately returns the index value of the element returning true. FindIndex returns - 1 if no element in the array returns true.
findIndex does not change the array object.

[1,2,3].findIndex(function(x) { x == 2; });
// Returns index value 1

[1,2,3].findIndex(x => x == 4);
// Returns the index value - 1.

12.keys,values,entries

ES6 provides three new methods -- entries(), keys(), and values() -- for traversing arrays. They all return a traversal object, which can be traversed by a for...of loop. The only difference is that keys() is the traversal of key names, values() is the traversal of key values, and entries() is the traversal of key-value pairs.

for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0 "a"
// 1 "b"

Topics: Javascript IE