使用JavaScript对逗号分隔的字符串数组进行排序

Cod*_*ady 1 javascript arrays sorting split array-map

我遇到了一个奇怪的要求,我在最后几个小时努力完成它.下面是我的字符串数组(只是一个例子,实际数组包含大约2500条记录):

var testArray = [
  "130,839.9,855,837.3,848.65,3980489", 
  "129,875,875,828.1,833.25,6926078", 
  "138,891.3,893.3,865.2,868.75,5035618"
]
Run Code Online (Sandbox Code Playgroud)

我们这里有3个元素,每个元素是comma分开的(每个元素有6个项目).即:

testArray[0] = "130,839.9,855,837.3,848.65,3980489"
Run Code Online (Sandbox Code Playgroud)

我的问题是,我想testArray根据每个元素的第一项进行排序,并将其转换为具有所有值的数组的数组为float,因此输出将是:

[
  [129, 875, 875, 828.1, 833.25, 6926078],
  [130, 839.9, 855, 837.3, 848.65, 3980489],
  [138, 891.3, 893.3, 865.2, 868.75, 5035618]
]
Run Code Online (Sandbox Code Playgroud)

我能够对整个数组进行排序而不是整个数组,我尝试使用拆分然后排序而没有运气.

有人可以帮我解决这个问题,如果我不清楚,请告诉我.

Ric*_*ick 8

Array#map在a中Array#map使用Array#sort转换数组,然后根据[0]indices(a[0] - b[0])在转换后的数组上使用:

在ES5中

var testArray = [
  "130,839.9,855,837.3,848.65,3980489", 
  "129,875,875,828.1,833.25,6926078", 
  "138,891.3,893.3,865.2,868.75,5035618"
]

var converted = testArray.map(function (item) {
  return item.split(',').map(function (num) {
    return parseFloat(num);
  });
})
console.log(converted)

var sorted = converted.sort(function (a, b) { return a[0] - b[0] })
console.log(sorted)
Run Code Online (Sandbox Code Playgroud)

在ES6中

const testArray = [
  "130,839.9,855,837.3,848.65,3980489", 
  "129,875,875,828.1,833.25,6926078", 
  "138,891.3,893.3,865.2,868.75,5035618"
]

const converted = testArray.map(
  item => item.split(',').map(
    num => parseFloat(num)
  )
)
console.log(converted)

const sorted = converted.sort((a, b) => a[0] - b[0])
console.log(sorted)
Run Code Online (Sandbox Code Playgroud)

在ES6(浓缩)

const testArray = [
  "130,839.9,855,837.3,848.65,3980489", 
  "129,875,875,828.1,833.25,6926078", 
  "138,891.3,893.3,865.2,868.75,5035618"
]

const convertedAndSorted = testArray
  .map(n => n.split(',')
  .map(num => parseFloat(num)))
  .sort((a, b) => a[0] - b[0])

console.log(convertedAndSorted)
Run Code Online (Sandbox Code Playgroud)