JavaScript 4/30: map array, filter and reduce usage

JavaScript30 a 30-day challenge Wes Bos introduced, designed to help people with pure JavaScript to achieve the effect, if you want fast beginner sophisticated in terms of JS, give it a try. Now you see is the first in the series of summary, I do not know when to finish 30 questions, not in this legislation vowed a flag. Fourth Question book entitled.

Achieve results

This section describes several commonly used methods for JS Array comprising filter (), map (), sort (), reduce (), and see the results in the Console panel. Where the document has been given two sets of arrays:

  • The first group: inventors array containing the name, last name, date of birth and date of death
const inventors = [
      { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
       ......
      { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
    ];
  • Second set: people array, contains a set of names, separated by commas canning.
 const people = ['Beck, Glenn', ...... , 'Blake, William'];

Topics are as follows:

  1. Screening inventor born in the 16th century;
  2. As an array, list their name and surname;
  3. According to their date of birth and descending order;
  4. The combined total of all calculated inventor lived teens;
  5. Sorted according to their age;
  6. Using the website (https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris) given list includes Paris Avenue 'de' bytes;
  7. Sort by last name;
  8. The statistics of the number of each type of array.

Knowledge Point

filter()

Filtering, screening of all elements eligible, if it is true return to form a new array to the first question, for example:

    function bornyear(inventor) {
      return inventor.year >= 1500 && inventor.year < 1600;
    }
    var fifteen = inventors.filter(bornyear);
    console.table(fifteen);
    // 可简化为
    const fifteen = inventors.filter(inventor => (inventor.year >= 1500 && inventor.year < 1600));

map()

Mapping operation, for each element of the original array processing, and return the new array. To the second question, for example:

    const fullnames = inventors.map(inventor => `${inventor.first} ${inventor.last}`);
    console.table(fullnames);

sort()

Sorting operation, default sort order is a string of Unicode code points, such as before 10 2, and the number before and uppercase letters, uppercase letters before lowercase letters. Comparison function may also be used, in accordance with the array will call the function return values ​​are sorted in the following format:

    function compare(a, b) {
      if (a < b) {
        // 按某种排序标准进行比较, a 小于 b
        return -1;
      }
      if (a > b) {
        return 1;
      }
      // a must be equal to b
      return 0;
    }

Number instead of a string to be compared, the comparison function can be simply reduced to a B, as a function of the array will be in ascending order:

    function compareNumbers(a, b) {
      return a - b;
    }

For the third question, we can use relatively simple addition and subtraction:

    const birthdate = inventors.sort((inventora, inventorb) => (inventorb.year - inventora.year));
    console.table(birthdate)

The seventh question, you need to compare press Return:

    const sortName = inventors.sort((a, b) => {
      return (a.last > b.last) ? 1 : -1;
    })
    console.table(sortName);

reduce()

Merge operation, a total of two parameters, the first one is the function, can be understood as an accumulator, the accumulated return value through the array of return, and the second is the initial value. If no initial value, the first element in the array will be used. To the fourth question, for example:

   const totalyears = inventors.reduce((total, inventor) => { return total + (inventor.passed - inventor.year); }, 0);
    console.log(totalyears);

reduce () method used to speak the same Q8:

    const sumup = data.reduce(function (obj, item) {
      if (!obj[item]) {
        obj[item] = 0;
      }
      obj[item]++;
      return obj;
    }, {});

    console.log(sumup);

Notably, the first argument to the callback function may be a target, the number of each type of storage items. About the object. For in-depth understanding, reference Ruan Yifeng's blog .

map () and filter () binding

Referring Question 6, subject of the request at the site selected Paris Avenue containing 'de' byte; preferred acquisition element corresponding to the node, and converted into an array, reuse .includes () method can be obtained.

    const category = document.querySelector('.mw-category');
    const links = Array.from(category.querySelectorAll('a'));
    const de = links.map(link => link.textContent).filter(streetName => streetName.includes('de'));
    console.table(de)

Guess you like

Origin www.cnblogs.com/qianduanwriter/p/11794252.html