javascript 的 map/reduce

本文介绍了Google提出的MapReduce概念,详细解释了map和reduce函数在处理数据集时的应用,并提供了JavaScript示例来展示如何使用这些函数简化复杂的数据处理任务。

https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001435119854495d29b9b3d7028477a96ed74db95032675000

map/reduce


如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Processing on Large Clusters”,你就能大概明白map/reduce的概念。

map

举例说明,比如我们有一个函数f(x)=x2,要把这个函数作用在一个数组[1, 2, 3, 4, 5, 6, 7, 8, 9]上,就可以用map实现如下:

map

由于map()方法定义在JavaScript的Array中,我们调用Arraymap()方法,传入我们自己的函数,就得到了一个新的Array作为结果:

function pow(x) {
    return x * x;
}

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.map(pow); // [1, 4, 9, 16, 25, 36, 49, 64, 81]

map()传入的参数是pow,即函数对象本身。

你可能会想,不需要map(),写一个循环,也可以计算出结果:

var f = function (x) {
    return x * x;
};

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var result = [];
for (var i=0; i<arr.length; i++) {
    result.push(f(arr[i]));
}

的确可以,但是,从上面的循环代码,我们无法一眼看明白“把f(x)作用在Array的每一个元素并把结果生成一个新的Array”。

所以,map()作为高阶函数,事实上它把运算规则抽象了,因此,我们不但可以计算简单的f(x)=x2,还可以计算任意复杂的函数,比如,把Array的所有数字转为字符串:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arr.map(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']

只需要一行代码。

reduce

再看reduce的用法。Array的reduce()把一个函数作用在这个Array[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果就是:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

比方说对一个Array求和,就可以用reduce实现:

var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x + y;
}); // 25

练习:利用reduce()求积:

'use strict';

function product(arr) {
}

// 测试:
if (product([1, 2, 3, 4]) === 24 && product([0, 1, 2]) === 0 && product([99, 88, 77, 66]) === 44274384) {
    alert('测试通过!');
}
else {
    alert('测试失败!');
}

要把[1, 3, 5, 7, 9]变换成整数13579,reduce()也能派上用场:

var arr = [1, 3, 5, 7, 9];
arr.reduce(function (x, y) {
    return x * 10 + y;
}); // 13579

如果我们继续改进这个例子,想办法把一个字符串13579先变成Array——[1, 3, 5, 7, 9],再利用reduce()就可以写出一个把字符串转换为Number的函数。

练习:不要使用JavaScript内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数:

'use strict';

function string2int(s) {
}

// 测试:
if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
    if (string2int.toString().indexOf('parseInt') !== -1) {
        alert('请勿使用parseInt()!');
    } else if (string2int.toString().indexOf('Number') !== -1) {
        alert('请勿使用Number()!');
    } else {
        alert('测试通过!');
    }
}
else {
    alert('测试失败!');
}

练习

请把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']

'use strict';

function normalize(arr) {
}

// 测试:
if (normalize(['adam', 'LISA', 'barT']).toString() === ['Adam', 'Lisa', 'Bart'].toString()) {
    alert('测试通过!');
}
else {
    alert('测试失败!');
}

小明希望利用map()把字符串变成整数,他写的代码很简洁:

'use strict';

var arr = ['1', '2', '3'];
var r;
alert('[' + r[0] + ', ' + r[1] + ', ' + r[2] + ']');

结果竟然是[1, NaN, NaN],小明百思不得其解,请帮他找到原因并修正代码。

提示:参考Array.prototype.map()的文档


### 头歌平台中的 Map/Reduce 使用教程 #### 1. Map/Reduce 的基本概念 Map-Reduce 是一种用于大规模数据集并行处理的编程模型[^2]。它通过两个主要阶段来完成任务:`Map` 阶段负责将输入数据分割成键值对的形式,并对其进行初步处理;`Reduce` 阶段则接收来自 `Map` 输出的结果,进一步聚合这些结果以生成最终输出。 #### 2. Hadoop 中的 Map/Reduce 实现 在 Hadoop 生态系统中,Map/Reduce 被广泛用来解决复杂的大规模数据分析问题。当单个 Map/Reduce 作业无法满足需求时,可以通过链式调用的方式连接多个作业。具体来说,前一个作业的输出会被写入分布式文件系统 (DFS),而后一个作业可以直接读取该输出作为其输入[^1]。 以下是基于 Java 编写的简单 Hadoop Map/Reduce 示例代码: ```java public class WordCount { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line.toLowerCase()); while (tokenizer.hasMoreTokens()) { word.set(tokenizer.nextToken()); context.write(word, one); } } } public static class SumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(key, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(SumReducer.class); job.setReducerClass(SumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 此程序实现了经典的单词计数功能,其中 `TokenizerMapper` 将每条记录拆分为词语,而 `SumReducer` 则统计每个词出现的次数。 #### 3. JavaScript 中的 MapReduce 函数 除了传统的 Hadoop 平台外,在前端开发领域也可以利用 JavaScript 提供的内置高阶函数 `map()` 和 `reduce()` 来模拟类似的逻辑操作。例如下面这段脚本展示了如何使用这两个方法处理一组对象集合的数据[^4]: ```javascript const data = [ { gradeId: 'A', value: 85 }, { gradeId: 'B', value: 90 }, { gradeId: 'A', value: 75 }, ]; let res1 = new Map(); let list = []; data.forEach((item) => { if (res1.has(item.gradeId)) { res1.get(item.gradeId).value += item.value; } else { let newItem = { ...item }; list.push(newItem); res1.set(item.gradeId, newItem); } }); console.log(list); // [{gradeId: 'A', value: 160}, {gradeId: 'B', value: 90}] ``` 上述例子演示了怎样借助于 `forEach` 方法配合哈希表结构累积相同等级的成绩总分。 ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值