【问题标题】:Create Two Column Array From One Column Array Using Delimiter in JS在 JS 中使用分隔符从一列数组创建两列数组
【发布时间】:2017-07-21 06:28:21
【问题描述】:

我有一个包含经度和纬度的 JavaScript 数组。现在,我的数组是这种格式并且是数组类型:

[Lat,Lon]

[Lat,Lon]

[Lat,Lon]

我想将这个一列数组转换成具有这种格式的两列数组:

[Lat][Lon]

[Lat][Lon]

[Lat][Lon]

如何在 JS 中做到这一点?我最好的猜测涉及使用一列数组中的逗号作为分隔符,但我不确定如何实现这一点。我愿意使用 JQuery。

我尝试使用此代码拆分我的数据,但是

var getOutline = 'lat1,lon1/lat2,lon2/lat3,lon3'; //Sample
var temporaryArray = new Array();
temporaryArray = getOutline.split("/");
console.log(temporaryArray)

var temporaryArray2 = new Array();
temporaryArray2 = temp.split(",");
console.log(temporaryArray2)

但是,我的第二个不起作用,因为 split 函数不会拆分 Array 类型。

【问题讨论】:

  • 请向我们展示您自己的创作尝试
  • var _arr = []; arr.map(function(item){_arr.push(item.split(','))})
  • @CarstenLøvboAndersen 已编辑
  • 绝对使用 jQuery,它几乎可以做任何事情。

标签: javascript jquery arrays latitude-longitude delimiter


【解决方案1】:

如果需要,请尝试下一个{lat1: {lon1: value, lon2: ...}, ...}

var getOutline = 'lat1,lon1/lat2,lon2/lat3,lon3',
    result = {};

getOutline.split('/').forEach(function (coord) {
    var tmp = coord.split(',');
    result[tmp[0]][tmp[1]] = '{something that is needed as a value}';
});

或者,如果需要 [[lat1, lon1], [lat2, lon2], ...]:

var getOutline = 'lat1,lon1/lat2,lon2/lat3,lon3',
    result = [];

getOutline.split('/').forEach(function (coord) {
    result.push(coord.split(',').map(Number));
});

【讨论】:

  • 谢谢!您的第二个解决方案正是我所需要的。
  • 猜我误解了这个问题,因为这是你说你不想要的确切格式:[ "lat1", "lon1" ], [ "lat2", "lon2" ], [ "lat3", "lon3" ]
  • @AlexanderHiggins,我已经更新了将字符串转换为数字的回复
  • 它与字符串或数字无关。问题表明数据已经采用[Lat,Lon],但需要[Lat],[Lon] 格式,但随后接受的答案最终采用[Lat,Lon] 格式。只是 OP 的 split 功能有问题。这将误导新读者,假设他们可以使用此答案将[[Lat,Lon],[Lat,Lon] 格式化数据转换为二维数组。
【解决方案2】:

您可以通过数组进行映射并将每个值拆分为多个。

var array = [
  '1,2',
  '3,4',
];

var newArray = array.map(function(i) {
  return i.split(',');
});

// Returns an array of arrays
// [ [1, 2], [3, 4] ]

【讨论】:

  • 不确定这正是操作人员想要的
  • 是的,我也不完全确定,希望他能澄清一下。
猜你喜欢
  • 1970-01-01
  • 2019-11-11
  • 2017-02-03
  • 2019-10-07
  • 2018-02-21
  • 1970-01-01
  • 2017-04-02
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多