【发布时间】:2020-12-07 16:04:58
【问题描述】:
我正在练习数据结构和算法,但遇到了一个困扰我的问题。
您有一个输入数组,其中包含格式为“产品、销售量、价格”的元素。您需要返回一个数组,其中包含按销售量排序的所有产品。如果两种产品的销售量相同,请按最低价格排序。
我开始的方式是:
- 遍历数组,用逗号分割元素
- 将产品名称和价格添加到以销量为关键的产品对象中
- 跟踪最大销售量
- 从最大值开始,到零,如果有具有该键的产品,将名称和价格推送到我的返回数组中
- 返回数组
这至少给了我按销售量排序的产品。但是当我有销售相同数量的产品时,它就不起作用了。如果商品的销售量相同,我不确定按价格对它们进行排序的有效方法。
有人知道如何实现价格排序吗?或者解决这个问题的更好方法?
const items = [
'Chair, 100, 20',
'Sofa, 70, 200',
'Desk, 80, 120',
'Table, 400, 300',
'Fan, 10, 60',
'Pillow, 40, 5',
'Blanket, 40, 20',
'Rug, 100, 200',
'Mat, 2, 30',
'Stool, 80, 40',
'Comforter, 200, 250',
'Recliner, 50, 350',
];
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const productList = (items) => {
let returnArray = [];
let products = {};
let max = 0;
for (let i = 0; i < items.length; i++) {
let productItems = items[i].split(',');
let product = new Product(productItems[0].trim(), productItems[2].trim());
let orderAmt = parseInt(productItems[1].trim());
products[orderAmt] = product;
max = Math.max(max, productItems[1]);
}
while (max > 0) {
if (products[max]) {
returnArray.push(`${products[max].name}, ${max}, ${products[max].price}`);
}
max--;
}
return returnArray;
};
console.log(productList(items));
.as-console-wrapper { min-height: 100%!important; top: 0; }
【问题讨论】:
-
你已经拥有了一切。它就在你面前。方法是正确的。只需将每个产品的字符串版本映射到包含所有产品数据的项目。然后通过
sort和一个自定义比较函数对这个产品项目数组进行排序,首先比较amount sold,然后(如果相等)比较price,最后(如果再次相等)按姓名。
标签: javascript arrays algorithm sorting data-structures