[Javascript] Advanced Flattening
Really the trick to flattening deeply nested structures is to just keep nesting map expressions until you have a variable or function argument, when is basically the same thing here, a variable bound to every single item you need to create your result.
Because there are three nested map expressions, I am going to end up with a three dimensional collection. The first step is figuring out how many levels deep your collection is. The next step is to flatten it n-1 times.
If your collection is three dimensional, you need two concat alls. It also matters where you put the concat all. I can't put the concat all here because I want you to notice that this expression by itself is just a one dimensional collection. We're just taking an array of closes, filtering it, and then mapping it not into another collection but just into an object.
var exchanges = [ { name: "NYSE", stocks: [ { symbol: "XFX", closes: [ { date: new Date(2014,11,24), price: 240.10 }, { date: new Date(2014,11,23), price: 232.08 }, { date: new Date(2014,11,22), price: 241.09 } ] }, { symbol: "TNZ", closes: [ { date: new Date(2014,11,24), price: 521.24 }, { date: new Date(2014,11,23), price: 511.00 }, { date: new Date(2014,11,22), price: 519.29 } ] }, ] }, { name: "TSX", stocks: [ { symbol: "JXJ", closes: [ { date: new Date(2014,11,24), price: 423.22 }, { date: new Date(2014,11,23), price: 424.84 }, { date: new Date(2014,11,22), price: 419.72 } ] }, { symbol: "NYN", closes: [ { date: new Date(2014,11,24), price: 16.82 }, { date: new Date(2014,11,23), price: 16.12 }, { date: new Date(2014,11,22), price: 15.77 } ] }, ] } ]; Array.prototype.concatAll = function() { var results = []; this.forEach(function(subArray) { subArray.forEach(function(item) { results.push(item); }); }); return results; }; // Want to output the closes which the date is 12/24 var christmasEveCloses = exchanges. map(function(exchange){ return exchange.stocks .map(function(stock){ return stock.closes. filter(function(close){ return close.date.getMonth() === 11 && close.date.getDate() === 24; }) .map(function(close){ return { symbol: stock.symbol, price: close.price } }); }).concatAll(); }).concatAll(); christmasEveCloses.forEach(function(christmasEveClose) { console.log(christmasEveClose); });
相关文章
- javascript 高级教程 视频_精通JavaScript
- javascript html转换成markdown,如何使用Turndown使用JavaScript将HTML转换为Markdown[通俗易懂]
- 2017年 JavaScript 框架回顾 — 后端框架详解编程语言
- JavaScript的注入引出技术诈骗
- JavaScript学习笔记(十三)Dom创建表格
- JavaScript对象的属性和方法4种不同的类型
- JavaScript中获取元素索引的函数
- JavaScript学习笔记(二)js对象
- JavaScript高级程序设计阅读笔记(十六)javascript检测浏览器和操作系统-detect.js
- Javascript的数组与字典用法与遍历对象的属性技巧
- javascript中怎么做对象的类型判断
- 利用noesis.Javascript开源组件.Net中执行javascript脚本
- JavaScript简单实现鼠标拖动选择功能
- JavaScript异步编程Promise模式的6个特性
- 实例分析javascript中的call()和apply()方法