In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to carry out JavaScript data flattening analysis, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
What is flattening?
The flattening of an array is to convert a nested multi-layer array array (nesting can be any number of layers) into an array with only one layer.
For example, if there is a function called flatten that flattens the array, the effect would be as follows:
Var arr = [1, [2, [3,4]]; console.log (flatten (arr)) / / [1,2,3,4] cyclic array + recursion
Circular array + recursion
Implementation idea: circular array, if there are still arrays in the data, recursively call the flatten flat function (using for loop flattening), connect with concat, and finally return result
Function flatten (arr) {var result = []; for (var I = 0, len = arr.length; I)
< len; i++){ if(Array.isArray(arr[i])){ result = result.concat(flatten(arr[i])); }else{ result.push(arr[i]); } } return result; } flatten(arr) // [1,2,3,4]递归 我们最一开始能想到的莫过于循环数组元素,如果还是一个数组,就递归调用该方法: var arr = [1, [2, [3, 4]]]; function flatten(arr) { var result = []; for (var i = 0, len = arr.length; i < len; i++) { if (Array.isArray(arr[i])) { result = result.concat(flatten(arr[i])) } else { result.push(arr[i]) } } return result; } console.log(flatten(arr))tostring 如果数组的元素都是数字,那么我们可以考虑使用 toString 方法,因为: [1, [2, [3, 4]]].toString() // "1,2,3,4" 调用 toString 方法,返回了一个逗号分隔的扁平的字符串,这时候我们再 split,然后转成数字不就可以实现扁平化了 // 方法2var arr = [1, [2, [3, 4]]]; function flatten(arr) { return arr.toString().split(',').map(function(item){ return +item })} console.log(flatten(arr)) 然而这种方法使用的场景却非常有限,如果数组是 [1, '1', 2, '2'] 的话,这种方法就会产生错误的结果。 reduce 既然是对数组进行处理,最终返回一个值,我们就可以考虑使用 reduce 来简化代码: // 方法3var arr = [1, [2, [3, 4]]]; function flatten(arr) { return arr.reduce(function(prev, next){ return prev.concat(Array.isArray(next) ? flatten(next) : next) }, [])} console.log(flatten(arr)) ES6 增加了扩展运算符,用于取出参数对象的所有可遍历属性,拷贝到当前对象之中: var arr = [1, [2, [3, 4]]]; console.log([].concat(…arr)); // [1, 2, [3, 4]] 我们用这种方法只可以扁平一层,但是顺着这个方法一直思考,我们可以写出这样的方法: var arr = [1, [2, [3, 4]]]; function flatten(arr) { while (arr.some(item =>Array.isArray (item)) {arr = [] .concat (.arr);} return arr;} console.log (flatten (arr)) undercore
So how to write an abstract flat function to facilitate our development? so it's time for us to copy underscore.
The source code and comments are given directly here, but note that the flatten function here is not the final _ .flatten, and there is more configuration for flatten to facilitate multiple API calls.
/ * Array flattening * @ param {Array} input Array to be processed * @ param {boolean} shallow whether only one layer is flattened * @ param {boolean} whether the strict strictly handles elements The following explains * @ param {Array} output, which is a parameter passed to facilitate recursion * / function flatten (input, shallow, strict, output) {/ / output output = output is used when recursively used | | [] Var idx = output.length; for (var I = 0, len = input.length; I
< len; i++) { var value = input[i]; // 如果是数组,就进行处理 if (Array.isArray(value)) { // 如果是只扁平一层,遍历该数组,依此填入 output if (shallow) { var j = 0, len = value.length; while (j < len) output[idx++] = value[j++]; } // 如果是全部扁平就递归,传入已经处理的 output,递归中接着处理 output else { flatten(value, shallow, strict, output); idx = output.length; } } // 不是数组,根据 strict 的值判断是跳过不处理还是放入 output else if (!strict){ output[idx++] = value; } } return output;} 解释下 strict,在代码里我们可以看出,当遍历数组元素时,如果元素不是数组,就会对 strict 取反的结果进行判断,如果设置 strict 为 true,就会跳过不进行任何处理,这意味着可以过滤非数组的元素,举个例子: var arr = [1, 2, [3, 4]]; console.log(flatten(arr, true, true)); // [3, 4] 那么设置 strict 到底有什么用呢?不急,我们先看下 shallow 和 strct 各种值对应的结果: shallow true + strict false :正常扁平一层 shallow false + strict false :正常扁平所有层 shallow true + strict true :去掉非数组元素 shallow false + strict true : 返回一个[] 我们看看 underscore 中哪些方法调用了 flatten 这个基本函数: _.flatten 首先就是 _.flatten: _.flatten = function(array, shallow) { return flatten(array, shallow, false);}; 在正常的扁平中,我们并不需要去掉非数组元素。 _.union 该函数传入多个数组,然后返回传入的数组的并集, 举个例子: _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); =>[1, 2, 3, 101, 10]
If the parameter passed in is not an array, the parameter is skipped:
_ .union ([1,2,3], [101,2,1,10], 4,5)
= > [1, 2, 3, 101, 10]
To achieve this effect, we can flatten all incoming arrays and then de-duplicate them, because only arrays can be passed in. In this case, we can skip non-array elements passed in by directly setting strict to true.
Function unique (array) {return Array.from (new Set (array));} _ .union = function () {return unique (flatten (arguments, true, true));} _ .difference
Don't you think it's useful to mess with strict? let's take a look at another _. Difference:
The syntax is:
_ .difference (array, * others)
The effect is to fetch elements from the array array that do not exist in multiple other arrays. Like _. Union, elements that are not arrays are excluded.
For example:
_ .difference ([1,2,3,4,5], [5,2,10], [4], 3)
= > [1,3]
The implementation is also simple: flatten the array of others and filter out the values in array that are not in the flattened array:
Function difference (array,... rest) {rest = flatten (rest, true, true); return array.filter (function (item) {return rest.indexOf (item) =-1;})} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.