对具有“A / B”格式数字的数组进行排序?

时间:2018-03-30 11:19:24

标签: javascript java arrays sorting

我有一个像arr = ["1/8", "2/8", "1/17", "4/17", "3/5", "1/2"]这样的数组 现在我需要获得一个像

这样的排序数组
[
"1/17",
"4/17",
"1/8",
"2/8",
"3/5",
"1/2"
]

所以任何人都有任何好的建议?提前谢谢!

PS:这只是一个例子,也许数据是其他数据,但都是A / B格式。

3 个答案:

答案 0 :(得分:3)

在js中,您可以使用sort

var arr = ["1/8", "2/8", "1/17", "4/17", "3/5", "1/2"];

arr.sort((a, b) => {
  let aParts = a.split("/");
  let bParts = b.split("/");

  //Given value A/B

  if (aParts[1] === bParts[1]) return aParts[0] - bParts[0]; //Check if B is the same, if it is use A to sort
  return bParts[1] - aParts[1];                              //B is not the same, so sort using b
});

console.log(arr);

更短的版本:

var arr = ["1/8", "2/8", "1/17", "4/17", "3/5", "1/2"];

arr.sort((a, b) => {
  let x = a.split("/"),y = b.split("/");
  return x[1] === y[1] ? x[0] - y[0] : y[1] - x[1];
});

console.log(arr);

答案 1 :(得分:0)

您可以使用Array.sort方法进行排序,split()排序适用于/之后的第二个元素。

  

在ES5中



var result = ["1/8", "2/8", "1/17", "4/17", "3/5", "1/2", '1/2'].sort(function(a, b) {
  if (a == b) {
    console.log('value same', a, b);
    return 0
  }
  a = parseInt(a.split('/')[1]);
  b = parseInt(b.split('/')[1]);
  return a > b ? -1 : (a < b ? 1 : 0);
});

console.log(result)
&#13;
&#13;
&#13;

  

在ES6中

&#13;
&#13;
let result= ["1/8", "2/8", "1/17", "4/17", "3/5", "1/2",'2/8'].sort((a, b) => {
 if (a == b) {
    console.log('value same',a,b);
    return 0
  }
  a = +a.split('/')[1];
  b = +b.split('/')[1];
  return a > b ? -1 : (a < b ? 1 : 0);
});

console.log(result)
&#13;
&#13;
&#13;

答案 2 :(得分:0)

arr = [“1/8”,“2/8”,“1/17”,“4/17”,“3/5”,“1/2”]

创建一个hashMap或任何可以保存键值对的数据结构(假设名称是arrMap)

创建一个可以保存浮点值的数组(假设名称是tempArray)

loop: arr elements

1st element is 1/8

    Use substring method to get before slash and after slash values
    Hence u will get
      Var beforeSlash = 1 // in string format

      Var afterSlash = 8     // in string format

      These are in string hence Do parseInt     

         Var beforeSlash = 1 // in int format

         Var afterSlash = 8  // in int format

         Var division =  beforeSlash / afterSlash; // division is in float

         Put in arrMap the value division with key “ beforeSlash / afterSlash” 
         [here it will be  key: value is “1/8” : 0.125]
         Put division in tempArray. // tempArray [0.125] 
end loop

在执行后,tempArray将是[0.125,0.25,0.0588,0.235,0.6,0.5]

应用任何默认排序方法

例如。 tempArray.sort()

最终的tempArray将变为[0.0588,0.125,0.235,0.25,0.5,0.6]

在执行之后,arrMap将

[

“1/8”:0.125,

“2/8”:0.25,

“1/17”:0.0588,

“4/17”:0.235,

“3/5”:0.6,

“1/2”:0.5

用hashMap中的键替换tempArray值

因此,finalArry成为了 [“1/17”,“1/8”,“4/17”,“2/8”,“1/2”,“3/5”]