原文中部分源码来源于:JS Array.reduce 实现 Array.map 和 Array.filter

Array 中的高阶函数 ---- map, filter, reduce


map() - 映射

var newArr = array.map((currentValue, index, array) => { return ... }, thisValue);
  • currentValue, 必须,当前的元素值;
  • index, 可选,当前元素值的索引;
  • array, 可选,原数组;
  • thisValue, 可选,对象作为该执行回调时使用,传递给函数,用作 "this" 的值;
  • return 新数组;

栗子:

var array1 = [1,4,9,16];
const map1 = array1.map(x => x *2); console.log(array1); // [1,4,9,16]
console.log(map1); // [2,8,18,32]

注意:

  1. map() 不会对空数组进行检测;

filter() - 过滤,筛选

var newArr = array.filter((currentValue, index, array) => { return ... }, thisValue);
  • currentValue, 必须,当前的元素值;
  • index, 可选,当前元素值的索引;
  • array, 可选,原数组;
  • thisValue, 可选,对象作为该执行回调时使用,传递给函数,用作 "this" 的值;
  • return 新数组;

栗子:过滤不符合项

var arr = [20,30,50, 96,50]
var newArr = arr.filter(item => item>40) console.log(arr) // [20,30,50, 96,50]
console.log(newArr) // [50, 96, 50]

高频用途:

  1. 上例中的过滤不符合项;
  2. 去掉数组中的 空字符串、0、undefined、null;
    var arr = ['1', '2', null, '3.jpg', null, 0]
    var newArr = arr.filter(item => item)
    // 也可以写成
    // var newArr = arr.filter(Boolean);
    console.log(newArr) // ["1", "2", "3.jpg"]
  3. 数组去重;

注意:

  1. filter() 不会对空数组进行检测;

reduce - 累计

var result = array.reduce((total, currentValue, currentIndex, array) => { return ... }, initialValue);
  • total, 必须,初始值,第一次循环之后是计算后的返回值;
  • currentValue, 必须,当前的元素值;
  • currentIndex, 可选,当前元素值的索引;
  • array, 可选,原数组;
  • initialValue, 可选,传递给函数的初始值,即此值会在第一次循环之前赋值给 total;
  • return 经过处理过的 total;

栗子:统计字符串中每个字符出现的次数

const str = '9kFZTQLbUWOjurz9IKRdeg28rYxULHWDUrIHxCY6tnHleoJ'
const obj = {}
Array.from(str).reduce((accumulator, current) => {
current in accumulator ? accumulator[current]++ : accumulator[current] = 1
return accumulator;
}, obj)

当然,非 reduce 的写法是:

const str = '9kFZTQLbUWOjurz9IKRdeg28rYxULHWDUrIHxCY6tnHleoJ'
const obj = {}
str.split('').forEach(item => {
obj[item] ? obj[item]++ : obj[item] = 1
})

reduce 的用途很广泛,可以说,js 中有关数组循环的模块都可以使用 reduce 来实现,这里不一一列举,详见 reduce-MDN

js 实现 map


原生 js 实现:

Array.prototype.myMap = function(fn, context = window) {
if (typeof fn !== 'function') return;
let newArr = [];
for(let i = 0, len = this.length; i < len; i++) {
newArr.push(fn.call(context, this[i], i, this))
}
return newArr;
} // 使用
[1,2,3].myMap(function(v, i, arr) {
console.log(v, i, arr);
return v * 2;
})

有一点奇怪的是,需要先在 Array 上挂 myMap() 这个方法,然后回车后才能使用,如果将上述代码全部复制进浏览器控制台,回车运行会报错,这是为什么?

使用 reduce 实现:

Array.prototype.reduceMap = function(fn, context = window) {
if (typeof fn !== 'function') return;
// or if (typeof fn !== 'function') throw new TypeError(fn + 'is not a function') ;
let _this = this;
let newArr = _this.reduce(function(total, cV, cI, _this) {
return total.concat([fn.call(context, cV, cI, _this)])
}, [])
return newArr
}

上面的示例是挂载在 Array 上的,下面这个示例是函数式编程示例:

let fpReduceMap = (fn, context = window) => {
return targetArr => {
if (typeof fn !== 'function') throw new TypeError(fn + 'is not a function')
if (!Array.isArray(targetArr)) throw new TypeError('targetArr must be a Array')
if (targetArr.length == 0) return [];
return targetArr.reduce((total, cV, cI, targetArr) => {
return total.concat([fn.call(context, cV, cI, targetArr)])
}, [])
}
}
// 使用
fpReduceMap(function(v) {
console.log(this);
return v + 1;
}, {msg: 'mapping'})([1,2,3])

js Array 中的 map, filter 和 reduce的更多相关文章

  1. JS中的 map, filter, some, every, forEach, for in, for of 用法总结和区别

    JS中的 map, filter, some, every, forEach, for in, for of 用法总结和区别  :https://blog.csdn.net/hyupeng1006/a ...

  2. Map,Filter和Reduce

    转自:https://www.aliyun.com/jiaocheng/444967.html?spm=5176.100033.1.13.xms8KG 摘要:Map,Filter和Reduce三个函数 ...

  3. Python Map, Filter and Reduce

    所属网站分类: python基础 > 函数 作者:慧雅 原文链接: http://www.pythonheidong.com/blog/article/21/ 来源:python黑洞网 www. ...

  4. [译]PYTHON FUNCTIONS - MAP, FILTER, AND REDUCE

    map, filter, and reduce Python提供了几个函数,使得能够进行函数式编程.这些函数都拥有方便的特性,他们可以能够很方便的用python编写. 函数式编程都是关于表达式的.我们 ...

  5. Angularjs在控制器(controller.js)的js代码中使用过滤器($filter)格式化日期/时间实例

    Angularjs内置的过滤器(filter)为我们的数据信息格式化提供了比较强大的功能,比如:格式化时间,日期.格式化数字精度.语言本地化.格式化货币等等.但这些过滤器一般都是在VIEW中使用的,比 ...

  6. Python中的map()函数和reduce()函数的用法

    Python中的map()函数和reduce()函数的用法 这篇文章主要介绍了Python中的map()函数和reduce()函数的用法,代码基于Python2.x版本,需要的朋友可以参考下   Py ...

  7. hive优化之——控制hive任务中的map数和reduce数

    一.    控制hive任务中的map数: 1.    通常情况下,作业会通过input的目录产生一个或者多个map任务.主要的决定因素有: input的文件总个数,input的文件大小,集群设置的文 ...

  8. Map, filter and reduce

    To add up all the numbers in a list, you can use a loop like this: Total is initialized to 0. Each t ...

  9. 【原】javascript笔记之Array方法forEach&map&filter&some&every&reduce&reduceRight

    做前端有多年了,看过不少技术文章,学了新的技术,但更新迭代快的大前端,庞大的知识库,很多学过就忘记了,特别在项目紧急的条件下,哪怕心中隐隐约约有学过一个方法,但会下意识的使用旧的方法去解决,多年前ES ...

随机推荐

  1. epoll——IO多路复用选择器

    上上篇博客讲的套接字,由于其阻塞性而导致一个服务端同一时间只能与一个客户端连接.基于这个缺点,在上篇博客我们将其设置为非阻塞实现了一个服务端同一时间可以与多个客户端相连,即实现了并发,但其同样留下了一 ...

  2. 小白学习之pytorch框架(5)-多层感知机(MLP)-(tensor、variable、计算图、ReLU()、sigmoid()、tanh())

    先记录一下一开始学习torch时未曾记录(也未好好弄懂哈)导致又忘记了的tensor.variable.计算图 计算图 计算图直白的来说,就是数学公式(也叫模型)用图表示,这个图即计算图.借用 htt ...

  3. 了解Kafka生产者

    了解Kafka生产者 ​ 之前对kafka的整体架构有浅显的了解,这次正好有时间,准备深入了解一下kafka,首先先从数据的生产者开始吧. 生产者的整体架构 ​ 可以看到整个生产者进程主要由两个线程进 ...

  4. nginx反代及后端web配置

    一.反代配置,proxy_pass指向的upstream需要在反代的nginx.conf中配置 server {access_log /home/nginx/front_access.log;erro ...

  5. centos7 安装gdb (调试nginx)

    首先卸载原有的gdb,sudo yum remove gdb 从gnu官网下载最新的gdb源文件,wget http://mirrors.ustc.edu.cn/gnu/gdb/gdb-7.9.1.t ...

  6. PTC【Creo OR Proe】添加参数的方法

    Dim model As IpfcModel Try model = CoCreoAsyncConnection.Session.CurrentModel If model Is Nothing Th ...

  7. HDU-1875 畅通工程再续(最小生成树+判断是否存在)

    http://acm.hdu.edu.cn/showproblem.php?pid=1875 Problem Description 相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛 ...

  8. zeroc ice log4net 多进程log文件问题

    使用zeroc ice 中的icebox 的时候多服务会有多个服务实例,每个实例都要写日志文件,所以要配置多个日志文件区分开来, 类似这样  orderservice_1_20160101.log   ...

  9. 吴裕雄--天生自然TensorFlow高层封装:使用TensorFlow-Slim处理MNIST数据集实现LeNet-5模型

    # 1. 通过TensorFlow-Slim定义卷机神经网络 import numpy as np import tensorflow as tf import tensorflow.contrib. ...

  10. 用shell脚本生成at一次性的计划任务

    用shell生成一次性计划任务,这个任务就是执行另一个脚本 #!/bin count=`grep "sh /usr/local/sbin/iptables.sh" /var/spo ...