对列上的 2D 数组进行排序,其中重复项将重复项移动到顶部 JavaScript / Google 脚本

问题描述 投票:0回答:1

我需要对包含重复项的列上的二维数组进行排序,将重复项移动到顶部。

我可以使用以下方法按降序对 2D 数组进行排序:

values.sort((a, b) => a[2].localeCompare(b[2]));

但是如何将重复项移动到顶部,并保持其排序顺序?

X1  Z9  [email protected]
X3  Z7  [email protected]
X4  Z6  [email protected]
X5  Z1  [email protected]
X5  Z7  [email protected]
X7  Z2  [email protected]
X8  Z6  [email protected]
X9  Z5  [email protected]
X9  Z8  [email protected]

排序后:

X5  Z1  [email protected]
X7  Z2  [email protected]
X9  Z5  [email protected]
X4  Z6  [email protected]
X8  Z6  [email protected]
X3  Z7  [email protected]
X5  Z7  [email protected]
X9  Z8  [email protected]
X1  Z9  [email protected]

需要

X7  Z2  [email protected]
X9  Z5  [email protected]
X4  Z6  [email protected]
X8  Z6  [email protected]
X3  Z7  [email protected]
X5  Z7  [email protected]
X5  Z1  [email protected]
X9  Z8  [email protected]
X1  Z9  [email protected]
javascript sorting google-apps-script multidimensional-array
1个回答
0
投票

解决方法:

我的方法是提取二维数组的最后一列,根据您的首选输出对其进行排序,然后根据该列对二维数组进行排序。

尝试这个代码片段:

function sortArray() {
  var values = [ [ 'X1', 'Z9', '[email protected]' ],
  [ 'X3', 'Z7', '[email protected]' ],
  [ 'X4', 'Z6', '[email protected]' ],
  [ 'X5', 'Z1', '[email protected]' ],
  [ 'X5', 'Z7', '[email protected]' ],
  [ 'X7', 'Z2', '[email protected]' ],
  [ 'X8', 'Z6', '[email protected]' ],
  [ 'X9', 'Z5', '[email protected]' ],
  [ 'X9', 'Z8', '[email protected]' ] ];

  //Extracts the the last column of the array
  var lastCol = values.map(a => a[2])

  //Extracts the duplicate elements of the last column
  var dup = lastCol.filter(a => lastCol.indexOf(a) != lastCol.lastIndexOf(a)).sort() 
  
  //Extracts the unique elements of the last column
  var unique = lastCol.filter(a => lastCol.indexOf(a) == lastCol.lastIndexOf(a)).sort()

  //combines the duplicate and unique elements, sorted to the preferred output.
  var sortOrder = dup.concat(unique);

  //sorts the 2d array based on sorted last column
  var sortedArray = values.sort((a,b) => sortOrder.indexOf(a[2]) - sortOrder.indexOf(b[2]))

  console.log(sortedArray)
}

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.