[Javascript] Create an Array concatAll method
JavaScript Array an create method
2023-09-14 08:59:21 时间
In addition to flat Arrays, programmers must often deal with nested Arrays. For example let's say we have an Array of stock exchanges, each of which is represented by an array of all the stocks listed on that exchange. If we were looking for a stock that matched a certain criteria, we would first need to loop through all of the exchanges, and then all of the stocks within.
In these situations, most developers would nest two loops. However in this lesson we will write a new Array function "concatAll" which will automatically flatten nested arrays buy one dimension. This will remove the need to ever use a nested loop to flatten a nested array.
var exchanges = [ [ { symbol: "XFX", price: 240.22, volume: 23432 }, { symbol: "TNZ", price: 332.19, volume: 234 } ], [ { symbol: "JXJ", price: 120.22, volume: 5323 }, { symbol: "NYN", price: 88.47, volume: 98275 } ] ]; Array.prototype.concatAll = function() { var results = []; this.forEach(function(subArray) { subArray.forEach(function(item) { results.push(item); }); }); return results; }; var stocks = exchanges.concatAll(); stocks.forEach(function(stock) { console.log(JSON.stringify(stock)); });
Also see lodash flatten:
_.flatten(array, [isDeep])
https://lodash.com/docs#flatten
相关文章
- javascript 基础_JavaScript高级编程
- javascript refresh page 几种页面刷新的方法[通俗易懂]
- Javascript Array forEach()中无法return和break,代替方法some()与every()「建议收藏」
- JavaScript Array(数组)对象中指定元素的删除
- 【说站】javascript中Array.slice()如何使用
- javascript html转换成markdown,如何使用Turndown使用JavaScript将HTML转换为Markdown[通俗易懂]
- JavaScript学习总结(二十)——Javascript非构造函数的继承详解编程语言
- JavaScript学习总结(十六)——Javascript闭包(Closure)详解编程语言
- JavaScript学习总结(九)——Javascript面向(基于)对象编程详解编程语言
- JavaScript正则表达式练习详解编程语言
- 最全 JavaScript Array 方法 详解
- JavaScript中Array对象相关的几个方法
- JavaScript实现??打印?理
- Javascript阻止javascript事件冒泡,获取控件ID值
- JavaScript应用技巧集合[推荐]
- javascript日期常用的方法
- JavaScript判断判断某个对象是Object还是一个Array
- javascript获取页面的高度及滚动条的位置的代码
- JavaScript设计模式富有表现力的Javascript(一)
- Javascript面向对象编程(三)非构造函数的继承
- Javascript异步加载详解(浏览器在javascript的加载方式)
- Javascript中判断变量是数组还是对象(array还是object)
- javascript:FF/Chrome与IE动态加载元素的区别说明
- javascript实现json页面分页实例代码
- Javascript学习笔记之函数篇(二):this的工作机制
- JavaScript中伪协议javascript:使用探讨
- Javascript基础教程之数组array