无法使用JavaScript按最大值对数组进行排序

时间:2019-07-15 10:29:38

标签: javascript arrays

我正在尝试使用JavaScript按照最大值对数组值进行排序,但是给我错误的结果。这是我的代码:

import UIKit
struct Product {
 var price = 0
}

class TicketBookingVC: UIViewController , UITableViewDelegate,       UITableViewDataSource {

@IBOutlet weak var tblView: UITableView!
@IBOutlet weak var mainTblView: UIView!

var bookingDetails = NSDictionary()
var paymentDetails = NSDictionary()
var arrPaymentDetails = NSArray()
var productArray = [Product]()
var product : Product!
private var counterValue = 1
var productIndex = 0
var counterLbl = UILabel()

@IBOutlet weak var bookBtn: UIButton!
@IBOutlet weak var eventImg: UIImageView!


override func viewDidLoad() {
    super.viewDidLoad()

    tblView.delegate = self
    tblView.dataSource = self


    let payment = self.paymentDetails.value(forKey: "payment") as! NSArray
    self.arrPaymentDetails = payment as NSArray

    for _ in 0...10{
        productArray.append(Product(price: 1))
    }

    // Do any additional setup after loading the view.
}

func numberOfSections(in tableView: UITableView) -> Int {

    return 3
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if section == 0 {
        return 1
    }
    else if section == 1{
        return arrPaymentDetails.count
    }
    else{
        return 1
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.section == 0 {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellfirst", for: indexPath)


        cell.selectionStyle = .none
        return cell
    }
  else if indexPath.section == 1 {

       let cell = tableView.dequeueReusableCell(withIdentifier: "cellsecond", for: indexPath)

        let mainViewCell = cell.contentView.viewWithTag(2000) as! UIView
        let normalView = cell.contentView.viewWithTag(2001) as! UIView
        let eventName = cell.contentView.viewWithTag(2003) as! UILabel
        let eventPrice = cell.contentView.viewWithTag(2004) as! UILabel
        counterLbl = cell.contentView.viewWithTag(2007) as! UILabel
        let decrementBtn = cell.contentView.viewWithTag(2005) as! UIButton
        let incrementBtn = cell.contentView.viewWithTag(2006) as! UIButton

        let dictAllDetails = self.arrPaymentDetails.object(at: indexPath.row) as! NSDictionary
        print("dictallgroups : \(dictAllDetails)")

        if dictAllDetails.value(forKey: "label") != nil {

            eventName.text = dictAllDetails.value(forKey: "label") as! String
        }
        else{
            eventName.text = ""
        }

        if dictAllDetails.value(forKey: "price") != nil {

            eventPrice.text = "₹ \(dictAllDetails.value(forKey: "price") as! String)"
        }
        else{
            eventPrice.text = "₹ 0"
        }

        decrementBtn.addTarget(self, action:#selector(self.decrementbuttonClicked), for: .touchUpInside)
        incrementBtn.addTarget(self, action:#selector(self.incrementbuttonClicked), for: .touchUpInside)

        product = productArray[indexPath.row]
        counterLbl.text = "\(product.price)"
        productIndex = indexPath.row

       cell.selectionStyle = .none
       return cell
  }
    else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellthird", for: indexPath)


        cell.selectionStyle = .none
        return cell
    }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    if indexPath.section == 0{

        return UITableView.automaticDimension
    }
    else{
        return 80
        //return UITableView.automaticDimension
    }
}

@objc func decrementbuttonClicked() {
    print("Button decrement")
    if(counterValue != 1){
        counterValue -= 1;
    }
    print("\(counterValue)")
    self.counterLbl.text = "\(counterValue)"
    product.price = counterValue
    print("\(product.price)")
    addProductToCart(product: product, atindex: productIndex)
}

@objc func incrementbuttonClicked() {
    print("Button increment")
    counterValue += 1;
    print("\(counterValue)")
    self.counterLbl.text = "\(counterValue)"
    product.price = counterValue
    print("\(product.price)")
    addProductToCart(product: product, atindex: productIndex)
}

func addProductToCart(product: Product, atindex: Int) {
    productArray[atindex] = product

    calculateTotal()
}

func calculateTotal()
{
    var totalValue = 0
    for objProduct in productArray {

        totalValue += objProduct.price
    }

   // self.totalLabel.text = "Total \(totalValue)"
}

在这里,我试图对值进行排序,例如function myFunction() { var inputdata = [ [1001, 20], [1002, 30], [1001, 50], [1003, 30], [1002, 60], [1003, 40], [1001, 70] ]; var storedata = []; for (var i = 0; i < inputdata.length; i++) { if (i === 0) { var data = { 'key': inputdata[i][0], 'value': inputdata[i][1] }; storedata.push(data); } else { for (var j = 0; j < storedata.length; j++) { if (storedata[j]['key'] == inputdata[i][0]) { if (storedata[j]['value'] < inputdata[i][1]) { storedata[j]['value'] = inputdata[i][1]; } break; } else { var data = { 'key': inputdata[i][0], 'value': inputdata[i][1] }; storedata.push(data); } } } } console.log(storedata); } 的最大值,但就我而言,预期结果没有到来。

2 个答案:

答案 0 :(得分:1)

因为在您的内部循环中,当您再次使用j遍历数组时,一个条目可能已经是您要查找的条目,但是所有您要遍历的其他对象不是,对于那些您正在重复的条目。换句话说:将else {部分移出循环,首先检查整个数组是否存在该条目,并且仅在不添加新数组的情况下:

  var exists = false;
  for(var j = 0; j < storeddata.length; j++) {
    if(/*...*/) {
      // merge
      exists = true;
      break;
    } // don't insert here
 }

 if(!exists) {
   // insert
 }

还不需要if(i === 0)部分(然后),因为storeddata将为空,因此它将直接进入if(!exists)部分并插入新条目。


我将其写为(确保您的方式也可以工作,并且可以如上所述进行修复):

 const result = [];

 for(const [key, value] of inputdata) {
   const duplicate = result.find(entry => entry.key === key);
   if(duplicate) {
     duplicate.value = Math.max(duplicate.value, value);
   } else {
     result.push({ key, value });
   }
}

答案 1 :(得分:0)

尚不清楚是要按数组的第一个排序,然后按数组的第二个排序,还是要简单列出子数组的唯一值,第一个值仅在此处排序,还是需要从子数组的第一个值。

因此,我将提供所有它们(按子数组中的两个值排序),然后提供第二个ALL值,然后是子数组第一个元素的唯一值的第三个。

var inputdata = [
  [1001, 20],
  [1002, 30],
  [1001, 50],
  [1003, 30],
  [1002, 60],
  [1003, 40],
  [1001, 70]
];

/* sort by the first and second values */
var sortedArray = inputdata.sort(function(a, b) {
  if (a[0] == b[0]) {
    return b[1] - a[1];
  }
  return b[0] - a[0];
}).reverse();
console.log(sortedArray);

/* just get the unique first values sorted */
let iA = [];
inputdata.forEach(function(element) {
  iA.push(element[0]);
});
/* all first values, sorted */
console.log(iA.sort());
/* unique first values sorted */
let uniqueSorted = [...new Set(iA)].sort();
console.log(uniqueSorted);