ios - 使用索引进行数字排序

标签 ios objective-c xcode

我想要对数字进行升序排序,包括它们的索引,这里我已经实现了这样的排序。

PriceArray =      [
      " 93",
      " 112.8",
      " 138.45",
      " 127.25",
      " 117.25",
      " 114.45"
    ]

通过使用这个,

NSArray *myArray = [priceArray sortedArrayUsingDescriptors:
                            @[[NSSortDescriptor sortDescriptorWithKey:@"doubleValue"
                                                            ascending:YES]]];

对这些数据进行排序后,结果如下

[
  " 93",
  " 112.8",
  " 114.45",
  " 117.25",
  " 127.25",
  "138.45"
]

但我想要对数据进行排序,包括像这样的索引

[
  [
    " 93",
    "0"
  ],
  [
    " 112.8",
    "1"
  ],
  [
    " 114.45",
    "5"
  ],
  [
    " 117.25",
    "4"
  ],
  [
    " 127.25",
    "3"
  ],
  [
    " 138.45",
    "2"
  ]
]

你能建议我如何实现这个吗?谢谢..

最佳答案

NSArray *priceArray =  @[
                   @" 93",
                   @" 112.8",
                   @" 138.45",
                   @" 127.25",
                   @" 117.25",
                   @" 114.45"
                   ];

NSMutableArray *output = [NSMutableArray new];

for(NSInteger i=0;i<[priceArray count];i++){

    NSArray *dataWithIndex = @[priceArray[i],@(i)];
    [output addObject:dataWithIndex];
}

NSArray *sorted = [output sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {

    return [[obj1 firstObject] doubleValue]>[[obj2 firstObject] doubleValue];
}];
NSLog(@"%@",sorted);

关于ios - 使用索引进行数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41018082/

相关文章:

ios - Swift ios 将多个项目连接到同一个 IBOutlet

ios - 使播放 Http 实时流媒体视频的 AVPlayer 静音

javascript - 通过应用程序级事件传递的 TIBlob 在接收端变为 NULL

objective-c - CBPeripheral 名称有时为空

ios - drawRect :中的EXC_BAD_ACCESS

xcode - 工作副本需要比 Xcode 支持的更新版本的 Subversion

ios - 如何在 ios sdk 中更改 facebook api 版本

ios - 滑入一个 UIButton 并在达到一定距离时按下另一个 UIButton

ios - 如何在 iPhone 中隐藏/显示带动画的 UIView

iphone - 如何同时执行两个 UI 更新?