原文中部分源码来源于: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. PAT Advanced 1127 ZigZagging on a Tree (30) [中序后序建树,层序遍历]

    题目 Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree c ...

  2. git 推送到github最常用命令

    初始化仓库,上传到github中. git init git add README.md git commit -m "first commit" git remote add o ...

  3. Go-简介-发展

    01-Go语言介绍 目录 Go语言介绍 Go语言特性 Go语言发展(版本/特性) Go语言应用 谁在用 应用领域 Go语言项目 Go语架构 Go语言发展前景 Go语言介绍 Go 即Golang,是Go ...

  4. ACM-ICPC Asia Beijing Regional Contest 2018 Reproduction hihocoder1870~1879

    ACM-ICPC Asia Beijing Regional Contest 2018 Reproduction hihocoder1870~1879 A 签到,dfs 或者 floyd 都行. #i ...

  5. gcc -E xx.c

    C语言代码在交给编译器之前,会先由预处理器进行一些文本替换方面的操作,例如宏展开.文件包含.删除部分代码等. 在正常的情况下,GCC 不会保留预处理阶段的输出文件,也即.i文件.然而,可以利用-E选项 ...

  6. 【Java杂货铺】JVM#虚拟机加载机制

    代码编译的结果从本地机器码变为字节码,是储存格式发展的一小步,却是编程语言发展的一大步--<深入理解Java虚拟机> 虚拟机把描述类的数据从Class文件加载到内存,并对数据进行校验.转化 ...

  7. 【网络流】Modular Production Line

    [网络流]Modular Production Line 焦作上的一道,网络流24题中的原题.... https://nanti.jisuanke.com/t/31715 给出了1e5个点,但是因为最 ...

  8. windows10+apache2.4+python3.6部署Django2.2.4项目

    刚从家回来,老师让写专利,就开始准备写,初稿交给老师后,把我说了一顿,我就想着回去改呀,然后...老师找到了我,说是食品院那急需一个展示数据的平台,然我尽快干出来,我也是菜鸟啊,就没单独干过呀,即使是 ...

  9. [NOIP 2002普及组]产生数(floyd+高精度)

    https://www.luogu.org/problem/P1037 题目描述 给出一个整数 n(n<1030) 和 k 个变换规则(k<=15). 规则: 一位数可变换成另一个一位数: ...

  10. [LC] 1002. Find Common Characters

    Given an array A of strings made only from lowercase letters, return a list of all characters that s ...