js Array 中的 map, filter 和 reduce
原文中部分源码来源于: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]
注意:
- 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]
高频用途:
- 上例中的过滤不符合项;
- 去掉数组中的 空字符串、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"] - 数组去重;
注意:
- 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的更多相关文章
- 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 ...
- Map,Filter和Reduce
转自:https://www.aliyun.com/jiaocheng/444967.html?spm=5176.100033.1.13.xms8KG 摘要:Map,Filter和Reduce三个函数 ...
- Python Map, Filter and Reduce
所属网站分类: python基础 > 函数 作者:慧雅 原文链接: http://www.pythonheidong.com/blog/article/21/ 来源:python黑洞网 www. ...
- [译]PYTHON FUNCTIONS - MAP, FILTER, AND REDUCE
map, filter, and reduce Python提供了几个函数,使得能够进行函数式编程.这些函数都拥有方便的特性,他们可以能够很方便的用python编写. 函数式编程都是关于表达式的.我们 ...
- Angularjs在控制器(controller.js)的js代码中使用过滤器($filter)格式化日期/时间实例
Angularjs内置的过滤器(filter)为我们的数据信息格式化提供了比较强大的功能,比如:格式化时间,日期.格式化数字精度.语言本地化.格式化货币等等.但这些过滤器一般都是在VIEW中使用的,比 ...
- Python中的map()函数和reduce()函数的用法
Python中的map()函数和reduce()函数的用法 这篇文章主要介绍了Python中的map()函数和reduce()函数的用法,代码基于Python2.x版本,需要的朋友可以参考下 Py ...
- hive优化之——控制hive任务中的map数和reduce数
一. 控制hive任务中的map数: 1. 通常情况下,作业会通过input的目录产生一个或者多个map任务.主要的决定因素有: input的文件总个数,input的文件大小,集群设置的文 ...
- 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 ...
- 【原】javascript笔记之Array方法forEach&map&filter&some&every&reduce&reduceRight
做前端有多年了,看过不少技术文章,学了新的技术,但更新迭代快的大前端,庞大的知识库,很多学过就忘记了,特别在项目紧急的条件下,哪怕心中隐隐约约有学过一个方法,但会下意识的使用旧的方法去解决,多年前ES ...
随机推荐
- Go-简介-发展
01-Go语言介绍 目录 Go语言介绍 Go语言特性 Go语言发展(版本/特性) Go语言应用 谁在用 应用领域 Go语言项目 Go语架构 Go语言发展前景 Go语言介绍 Go 即Golang,是Go ...
- 是时候写个自己的dialog了
组件下载地址:http://pan.baidu.com/s/1pJFVfej 最近做的项目需要用到对话框,但是原生的弹出框你是知道的.如果有时间,还是自己尝试一下,也是可以的. 一个简单图 里面的输入 ...
- 刘永富的Office/VBA/VSTO开发资源分享
各种常用安装包下载:https://share.weiyun.com/5PCvqY4 简称 文件名称 描述信息 视频课程 虚拟光驱软件Daemon DAEMON_Tools_Lite_V10.1.0. ...
- Office文档WEB端在线浏览(转换成Html)
最近在做了一个项目,要求是对Office文档在线预览.下面给大家分享一下我的方法. 1.第一种方法(不建议使用)我是在网上搜了一个利用COM组件对office文档进行转换,但是此方法必须要装Offic ...
- Collection接口介绍
Collection接口介绍 一个Collection代表一组对象,是集合体系中的根接口.一些允许有重复的元素一些不允许,一些有顺序一些没有顺序.JDK不提供此接口具体类的直接实现,只会有子接口和抽象 ...
- python 并发执行
并发执行, 精简代码. 适用python2 和python3 # -*- encoding:utf-8 -*- from threading import Thread from multiproce ...
- java.lang.IllegalArgumentException: Cannot format given Object as a Date
在进行日期转换的时候遇到了这个问题, 非常的恼火 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" ...
- voxelmorph配置
简介 VoxelMorph使用CNN实现了非监督的医学图像配准,速度较之前的方法有很大提升.主要特点有: 提出了一种基于学习的解决方案,不需要在训练过程中获取诸如ground truth对应或解剖标志 ...
- bat脚本修改dns(判断系统版本)
@echo off systeminfo if "%OS 名称%"=="%7%" goto windows7:windows7echo 正在设置本机主DNS , ...
- 九、linux-msyql下的mysql主从复制深度实战
1.上节基本诉说了mysql主从同步,这里想说明的是,其一从库在请求主库进行同步的时候,是主库的主线程进行用户名.密码的验证,在验证通过后,将请求转交给I/O线程负责同步:其二从库sql线程在读取中继 ...