This article focuses on the common array traversal methods: forEach, Map, filter, find, every, some, reduce. They have one thing in common: they do not change the original array.

The next steps are to implement some methods using the underlying array below:

  • cumulative
  • Than the size
  • Operations, respectively,
  • Find specific values and so on
let people = [
  {
    name: '马云'.money: 2000
  },
  {
    name: Ma Huateng.money: 1800
  },
  {
    name: Robin Li.money: 1500
  },
  {
    name: '我'.money: Infinity}];Copy the code

ForEach: Traverses the number group

ForEach is slightly different from the others in that all but forEach return a value. If you put a variable to the left of the equals sign, it will return undefined(it does not return any value).

var forEachLoop = people.forEach( function ( item, index, array ) {
	console .log(item, index, array); // (object, index, all array)
});
console .log(forEachLoop); // undefined
Copy the code

All other methods return a value or array, which in turn returns the original array value.

var mapLoop = people.map( function ( item, index, array ) {
  return item
});
console .log(mapLoop); // Same as the original array data
Copy the code

Map: Maps another array one by one

Map returns a new value to create a new array. Note that the number of returned values is the same as the length of the original array. Therefore, if you do not return, undefined is returned by default.

// Undefined without return
var mapEmpty = people.map( function ( item, index, array ) {});console .log(mapEmpty);     // [undefined, undefined, undefined, undefined]

var everyoneAdd = people.map( function ( item, index, array ) {
  item.money = item.money + 500 ; // Each money + 500
  return item;              // Return the object
});
console .log(everyoneAdd);   // Return the value after each processing, but remember that this is a reference feature that affects the original object
// {name: "ma Yun ", money: 2500}
// {name: "ma Huateng ", money: 2300}
// {name: "li Yanhong ", money: 2000}
// {name: "I ", money: Infinity}

var mapMoneyThan1500 = people.map( function ( item, index, array ) {
 // The length does not fit
 if (item.money > 1500 ) {
 return item;               // Get more than 1500}});console .log(mapMoneyThan1500);
// [{name: "ma ", money: 2000}, {name:" ma ", money: 1800}, undefined, {name: "I ", money: Infinity}]
Copy the code

Filter: Filters out the qualified elements in the array

Filter () detects numeric elements and returns an array of all elements that match the criteria. Filter () does not change the original array.

// filter
var filterEmpty = people.filter(function(item, index, array){});console.log(filterEmpty);    // If no condition is given, it will be an empty array

var filterMoneyThan1500 = people.filter(function(item, index, array){
  return item.money > 1500;       // Get more than 1500
});
console.log(filterMoneyThan1500); // Ma Yun, Ma Huateng, my three objects
Copy the code

Find: Returns the value of the first element of the eligible array

Find is used to find only one qualified object in an array. When more than two true values are returned, the first one takes precedence, usually for a particular ID. If no object matches the condition, undefined is returned.

var findEmpty = people.find(function(item, index, array){});console.log(findEmpty);          // undefined if there is no condition

var findMoneyThan1500 = people.find(function(item, index, array){
  return item.money > 1500;      // Get more than 1500
});
console.log(findMoneyThan1500);  // Only one object 'Ma Yun' will be returned

var findMe = people.find(function(item, index, array){
  return item.name === '我';    / / to find me
});
console.log(findMe);            // I am the object
Copy the code

Every: Verifies that every element in the array satisfies the specified condition

Verify all of the results. If all of the values are true, the result will be true; As long as one of these is false, false is returned.

var ans = people.every(function(item, index, array){
  return item.money > 1800;
});
console.log(ans); // false: If some parts do not match, the value is false

var ans2 = people.every(function(item, index, array){
  return item.money > 500;
});
console.log(ans2); // true: Everyone has more than 500 dollars
Copy the code

Some: Verifies that any elements in the array meet the specified criteria

Like the former, but returns true as long as part is true; The return value is false only if all are false.

var ans = people.some(function(item, index, array){
  return item.money > 1800;
});
console.log(ans); // true: true as long as some matches are true

var ans2 = people.some(function(item, index, array){
  return item.money < 500;
});
console.log(ans2); // false: Everyone has at least 500 dollars
Copy the code

Reduce: Combines the array into a value

Reduce is the most special among them. First of all, the parameter it returns is different from the previous one. It will receive the value returned by the previous one for the next object to use, which is very suitable for accumulation and comparison.

  • Accumulator: The previous parameter, if the first array, is passed in or initialized with an additional value
  • CurrentValue: current value
  • CurrentIndex: indicates the currentIndex
  • Array: all arrays
var reduceEmpty = people.reduce(function(accumulator, currentValue, currentIndex, array){});console.log(reduceEmpty);                 // undefined if there is no condition
Copy the code

You can add up all the values in the array by adding them to the previous one.

people.pop(); // My money is unfathomable, so remove it first
var reducePlus = people.reduce(function(accumulator, currentValue, currentIndex, array){
  // The previous return value, the current value, and the current index value respectively
  console.log(accumulator, currentValue, currentIndex);
  return accumulator + currentValue.money;  // Add to the previous value
}, 0);                                      // Pass in an initialization value of 0
console.log(reducePlus);                    // The total is 5300
Copy the code

You can also compare them and pick the highest value.

var reduceBestOne = people.reduce(function(accumulator, currentValue, currentIndex, array){
  console.log('reduce', accumulator, currentValue, currentIndex)
  return Math.max(accumulator, currentValue.money); // Which value is larger than the previous one
}, 0);
console.log(reduceBestOne);                  // The maximum value is 2000
Copy the code

Reduce is very powerful. Other traversal methods can be replaced by Reduce. Only examples of map being replaced by Reduce are listed here.

/ / the map method
var mapMoneyDouble = people.map( function ( item, index, array ) {
 return item.money*2;               / / double money
});
console .log(mapMoneyDouble); // 4000, 3600, 3000, Infinity

// The reduce method does the same thing
var reduceMoneyDouble = people.reduce( function ( accumulator, currentValue, currentIndex, array ) {             / / double money
  accumulator.push(currentValue.money*2);                / / double money
  return accumulator
},[]);
console .log(reduceMoneyDouble); // 4000, 3600, 3000, Infinity
Copy the code

If you find this article helpful, you are welcomeMy GitHub blogLike and follow, thank you!