简体   繁体   English

Javascript flatmap理解?

[英]Javascript flatmap understanding?

I'm not familiar with Javascript, but trying to essentially flatmap the following: 我不熟悉Javascript,但尝试基本平面化以下内容:

The spot where I see (5) [Array(2), Array(2), Array(2), Array(2), Array(2)] I want to appear like the others where they're all separated. 我看到的地方(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]我希望看起来像其他所有分开的地方。

0
:
(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
1
:
(2) [-112.2550785337791, 36.07954952145647]
2
:
(2) [-112.2549277039738, 36.08117083492122]
3
:
(2) [-112.2552505069063, 36.08260761307279]
4
:
(2) [-112.2564540158376, 36.08395660588506]
5
:
(2) [-112.2580238976449, 36.08511401044813]
6
:
(2) [-112.2595218489022, 36.08584355239394]
7
:
(2) [-112.2608216347552, 36.08612634548589]
8
:
(2) [-112.262073428656, 36.08626019085147]
9
:
(2) [-112.2633204928495, 36.08621519860091]
10
:
(2) [-112.2644963846444, 36.08627897945274]
11
:
(2) [-112.2656969554589, 36.08649599090644]

I have the following code: 我有以下代码:

let parsedGeoCoords = _.flatten(aoiList.map((aoi) => {
  return terraformer.parse(aoi.geo).coordinates
}), true)

New Attempt? 新的尝试? Messy 凌乱

let data = [
  [["1", "3"],["2", "5"],["3", "7"]],
  ["4", "5"],
  ["5", "56"]
]
function flatten(arr) {
  return arr.reduce(function (flat, toFlatten) {
    return flat.concat(is2DArray(toFlatten) ? (toFlatten) : [(toFlatten)]);
  }, []);
}

function is2DArray(arr) {
  return Array.isArray(arr[0])
}

console.log(flatten(data))

Input Data 输入数据

let data = [
  [["1", "3"],["2",3],["3","5"]],
  ["4", "5"],
  ["5", "56"],
  "4",
  "7"
]

Desire 欲望

[ [ '1', '3' ],
  [ '2', 3 ],
  [ '3', '5' ],
  [ '4', '5' ],
  [ '5', '56' ],
  [ '4', '7' ] ]

You can just fix the current output to match what you want. 您可以修复当前输出以匹配您想要的输出。 Just add: 只需添加:

var fullFlatten = _.flatten(_.map(data, function(elem) {
   return _.flatten(elem);
}));
var chunks = _.chunk(fullFlatten, 2);

With lodash you can simply use flattenDeep and then chunk : 使用lodash,你可以简单地使用flattenDeep然后使用chunk

 let data = [ [["1", "3"],["2",3],["3","5"]], ["4", "5"], ["5", "56"], "4", "7"] console.log(_.chunk(_.flattenDeep(data), 2)) // with no chaining // with chaining console.log( _(data) .flattenDeep() .chunk(2) .value() ) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM