zoukankan      html  css  js  c++  java
  • .map() .filter() .reduce() 的用法

    .map()

    让我用一些简单的例子来解释它是如何工作的。 如果说你收到一组包含多个对象的数组,每个对象是一个 person。最终你只希望得到一个只包含 id 的数组。

    // What you have
    var officers = [
      { id: 20, name: 'Captain Piett' },
      { id: 24, name: 'General Veers' },
      { id: 56, name: 'Admiral Ozzel' },
      { id: 88, name: 'Commander Jerjerrod' }
    ];
    // What you need
    [20, 24, 56, 88]
    

    我想你有多种方式来实现这个目标:.forEach() , .for(...of) ,或者 一个简单的 .for()

    让我们对比一下吧!

    用 .forEach()

    var officersIds = [];
    officers.forEach(function (officer) {
      officersIds.push(officer.id);
    });
    

    可以注意到,你不得不先创建一个空数组?让我们来看看.map()是如何做到的。

    var officersIds = officers.map(function (officer) {
      return officer.id
    });
    

    我们可以使用箭头函数做到更加的精简。

    const officersIds = officers.map(officer => officer.id);
    

    那么 .map() 是怎么运行的呢?实际上对数组的每个元素都遍历一次,同时返回一个新的值。记住一点是返回的这个数据的长度和原始数组长度是一致的。

    .filter()

    假如你有一个数组,你只想要这个数组中的一些元素怎么办呢?这时候 .filter() 就非常好用了。

    var pilots = [
      {
        id: 2,
        name: "Wedge Antilles",
        faction: "Rebels",
      },
      {
        id: 8,
        name: "Ciena Ree",
        faction: "Empire",
      },
      {
        id: 40,
        name: "Iden Versio",
        faction: "Empire",
      },
      {
        id: 66,
        name: "Thane Kyrell",
        faction: "Rebels",
      }
    ];
    

    如果我们现在想要两个数组:一个是 rebel 飞行员,一个是 Empire 飞行员,用 .filter() 将会非常简单~

    var rebels = pilots.filter(function (pilot) {
      return pilot.faction === "Rebels";
    });
    var empire = pilots.filter(function (pilot) {
      return pilot.faction === "Empire";
    });
    

    我们还可以用箭头函数更优雅的表达:

    const rebels = pilots.filter(pilot => pilot.faction === "Rebels");
    const empire = pilots.filter(pilot => pilot.faction === "Empire");
    

    总结:如果 callback 函数返回 true,这个元素将会出现在返回的数组中,如果返回 false 就不会出现在返回数组中

    .reduce()

    一个简单的例子,你就能感受到 .reduce() 的用法了。假如你有一个包含一些飞行员以及他们飞行经验的数组。

    var pilots = [
      {
        id: 10,
        name: "Poe Dameron",
        years: 14,
      },
      {
        id: 2,
        name: "Temmin 'Snap' Wexley",
        years: 30,
      },
      {
        id: 41,
        name: "Tallissan Lintra",
        years: 16,
      },
      {
        id: 99,
        name: "Ello Asty",
        years: 22,
      }
    ];
    

    如果你需要知道所有飞行员的总飞行年数。用 .reduce() 将会非常直观。

    var totalYears = pilots.reduce(function (accumulator, pilot) {
      return accumulator + pilot.years;
    }, 0);
    

    可以看到我们开始先用0初始化了我们的 accumulator 的值,如果需要我们可以用其他的值去初始化 accumulator 。 在对每个元素运行 callback 函数之后,reduce 将会返回最终值给我们(例子中:82)
    同样我们可以用箭头函数精简我们的代码:

    const totalYears = pilots.reduce((acc, pilot) => acc + pilot.years, 0);
    

    假如我们需要知道飞行员中飞行年限最长的那位,我们可以这样获取:

    var mostExpPilot = pilots.reduce(function (oldest, pilot) {
      return (oldest.years || 0) > pilot.years ? oldest : pilot;
    }, {});
    

    总结:reduce 可以直观的返回数组里面指定的一个值或者对象

    .map() .filter() .reduce() 结合使用

    因为 .map() 和 .filter()都返回一个数组,所以我们可以轻松的用链式编程的方法来综合使用它们。
    假设我们有如下数据:

    var personnel = [
      {
        id: 5,
        name: "Luke Skywalker",
        pilotingScore: 98,
        shootingScore: 56,
        isForceUser: true,
      },
      {
        id: 82,
        name: "Sabine Wren",
        pilotingScore: 73,
        shootingScore: 99,
        isForceUser: false,
      },
      {
        id: 22,
        name: "Zeb Orellios",
        pilotingScore: 20,
        shootingScore: 59,
        isForceUser: false,
      },
      {
        id: 15,
        name: "Ezra Bridger",
        pilotingScore: 43,
        shootingScore: 67,
        isForceUser: true,
      },
      {
        id: 11,
        name: "Caleb Dume",
        pilotingScore: 71,
        shootingScore: 85,
        isForceUser: true,
      },
    ];
    

    我们的目标是:获取属性为 force 的用户总值,读者可以先自行思考一下,用于巩固前面所学知识,我们可以如下处理。

    var totalJediScore = personnel
      .filter(function (person) {
        return person.isForceUser;
      })
      .map(function (jedi) {
        return jedi.pilotingScore + jedi.shootingScore;
      })
      .reduce(function (acc, score) {
        return acc + score;
      }, 0);
    

    同样,我们也可以用箭头表达式精简他们。

    const totalJediScore = personnel
      .filter(person => person.isForceUser)
      .map(jedi => jedi.pilotingScore + jedi.shootingScore)
      .reduce((acc, score) => acc + score, 0);


    链接:https://www.jianshu.com/p/e87b195f6943

  • 相关阅读:
    es手动创建索引,修改索引,删除索引
    es的scoll滚动查询技术
    es倒排索引和正排索引
    linux中按照指定内容查找文件
    es定制排序搜索结果
    es中如何定位不合法搜索
    es中filter和query的对比
    es组合多个条件进行查询
    手动建立mapping以及增加属性
    30分钟学会如何使用Shiro
  • 原文地址:https://www.cnblogs.com/ygyy/p/14631108.html
Copyright © 2011-2022 走看看