Talk about the array map, reduce, foreach, and Other methods

Source: Internet
Author: User
Tags prev

Tag: false equals SAR dev Red initialize ice parsing new

Talk about array traversal methods

There are several ways to iterate the JS array:

    • Every
    • Some
    • Filter
    • Foreach
    • Map
    • Reduce

Next, we will exchange each other.

Every ()

Arr.every (callback[, Thisarg])
return Value: TRUE | False
Whether to change the original array: Do not change the original array

Analytical:
The Every () method is used to test whether each item in the array passes the test of the callback function, and only returns true if all passes;
The callback that appear in this article are not specifically declared to represent a function that contains element, index, array three parameters.

Example:

// 检测数组中的所有元素是否都大于或等于100[].every((ele) => ele >= 100);  // true[1, 2, 3].every((ele) => ele >= 100);   // false
Some ()

Arr.some (callback[, Thisarg])
return Value: TRUE | False
Whether to change the original array: no change

Analytical:
Some () is similar to every (), except that every returns true for each entry through callback, while some returns callback as logic or true;some as long as there is a every.

Example:

function isBigEnough(element, index, array) {  return (element >= 10);}var passed = [2, 5, 8, 1, 4].some(isBigEnough);// passed is falsepassed = [12, 5, 8, 1, 4].some(isBigEnough);// passed is true
Filter ()

var newArr = Arr.filter (callback[, Thisarg])
Return value: New array
Whether to change the original array: Do not change the original array

Analytical:
The filter () method calls the callback function on each item in the array (which first has a value) and builds a new array (the array is a subset of the original array) based on the true or false returned by the call result.
That is, only the conforming (call callback returns True) is added to the new array.

Example:

const isBigEnough = value => value >= 10;let [...spread] = [12, 4, 8, 120, 44];let filtered = spread.filter(isBigEnough);// filtered: [12, 120, 44]// spread: [12, 4, 8, 120, 44]
ForEach ()

Array.foreach (callback[, Thisarg])
return value: undefined
Whether to change the original array: change to see callback

Analytical:
The ForEach () method executes the callback function once for each item in the array that has a valid value in ascending order, those that have been deleted (using the Delete method, and so on) or uninitialized items that are skipped (but not including those whose values are undefined) (for example, on sparse arrays). It's very rigid anyway.

Example:

// three 呢?它被跳过了,原因是到two时,使数组发生了变化,导致所有剩下的项上移一个位置,所以three被跳过了let words = [‘one‘, ‘two‘, ‘three‘, ‘four‘];words.forEach((word) => {    console.log(word);    if ( word === ‘two‘ ) {        words.shift();    }});// one// two// four
Map ()

Let NEWARR = Arr.map (callback[, Thisarg])
Return value: New array
Whether to change the original array: no change

Analytical:
The map () method is that each item in the array (with a value) is called the callback function in order, and then the return result of each item consists of a new array as the return value of the entire map method.

Example:

let str = ‘12345‘;Array.prototype.map.call(str, (x) => x).reverse().join(‘‘);// ‘54321‘
Reduce ()

Arr.reduce (callback[, InitialValue])
Return value: The result of the cumulative processing of the callback function
Whether to change the original array:

Analytical:
The callback of the reduce () method has four parameters, a cumulative return value more than previously said, and four parameters: accumulator, CurrentValue, Currentindex, array;initialvalue are used as the first call The value of the first parameter of callback, which uses the first element in the array by default.

The reduce () method is a bit similar to map, where each element in the array (a valid value) executes the callback function once, much more so that it will save the previous callback calculation as the next parameter.

If InitialValue is not provided, reduce starts execution of the callback method from the place of index 1, skipping the first index. If InitialValue is provided, start at index 0

Example:

// 求和let sum = [0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr, 0);// 计算数组中每个元素出现的次数let names = [‘Alice‘, ‘Bob‘, ‘Tiff‘, ‘Bruce‘, ‘Alice‘];let countedNames = names.reduce((allNames, name) => {    if ( name in allNames ) {        allNames[name]++;    } else {        allNames[name] = 1;    }    return allNames;}, {});// countedNames:// { ‘Alice‘: 2, ‘Bob‘: 1, ‘Tiff‘: 1, ‘Bruce‘: 1 }// 数组去重let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];let result = arr.sort().reduce((init, current) => {    // 主要是排了序    if ( init.length === 0 || init[init.length - 1] !== current ) {        init.push(current);    }    return init;}, []);console.log(result);
Reference

MDN Array

Talk about the array map, reduce, foreach, and Other methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.