【问题标题】:getting minimum value of a field in an array javascript获取数组javascript中字段的最小值
【发布时间】:2023-01-01 21:53:59
【问题描述】:

我有一系列项目,我只想从中提取该产品的最便宜版本。例如,我有两部 iPhone XS,但我只想提取较便宜的一部并将所有最便宜的物品添加到另一个数组中。下面是项目。

  const [items,setItems] = useState([
    {"itemid":"001" , "Product":"Iphone XS MAX PRO 512GB","Price" : 1200},
    {"itemid":"002" , "Product":"Samsung Galaxy S20 128GB","Price" : 700},
    {"itemid":"003" , "Product":"Huwaei x8 ","Price" : 600},
    {"itemid":"004" , "Product":"OPPO","Price" : 400},
    {"itemid":"005" , "Product":"Nokia","Price" : 200},
    {"itemid":"006" , "Product":"OPPO","Price" : 500},  
    {"itemid":"007" , "Product":"Iphone XS MAX PRO 512GB","Price" : 900},
  ])

如您所见,有两个 Oppo 项目和两个 iphone 项目。我只需要从它们中获得最便宜的版本以及其他其他项目。我该怎么做?

任何建议将不胜感激

【问题讨论】:

标签: javascript reactjs react-native


【解决方案1】:

const data = [
  {"itemid":"001" , "Product":"Iphone XS MAX PRO 512GB","Price" : 1200},
  {"itemid":"002" , "Product":"Samsung Galaxy S20 128GB","Price" : 700},
  {"itemid":"003" , "Product":"Huwaei x8 ","Price" : 600},
  {"itemid":"004" , "Product":"OPPO","Price" : 400},
  {"itemid":"005" , "Product":"Nokia","Price" : 200},
  {"itemid":"006" , "Product":"OPPO","Price" : 500},  
  {"itemid":"007" , "Product":"Iphone XS MAX PRO 512GB","Price" : 900},
];

const filtered = data.filter(item => /iphone xs/i.test(item.Product));
const result = filtered.reduce((prev, curr) => prev.Price < curr.Price ? prev : curr);

console.log(result);

要通过提供要搜索的数组和产品名称来创建返回最便宜商品(Price)的可重用函数:

// Utility function to escape regex sensitive characters
const regEscape = (str) => str.replace(/[/-\^$*+?.()|[]{}]/g, '\$&');

// Get cheapest product by Price given a Product name from array of products:
const getCheapest = (products, name) => {
  const filtered = products.filter(item => new RegExp(`\b${regEscape(name)}\b`, "i").test(item.Product));
  const result = filtered.reduce((prev, curr) => prev.Price < curr.Price ? prev : curr);
  return result;
};

const data = [
  {"itemid":"001" , "Product":"Iphone XS MAX PRO 512GB","Price" : 1200},
  {"itemid":"002" , "Product":"Samsung Galaxy S20 128GB","Price" : 700},
  {"itemid":"003" , "Product":"Huwaei x8 ","Price" : 600},
  {"itemid":"004" , "Product":"OPPO","Price" : 400},
  {"itemid":"005" , "Product":"Nokia","Price" : 200},
  {"itemid":"006" , "Product":"OPPO","Price" : 500},  
  {"itemid":"007" , "Product":"Iphone XS MAX PRO 512GB","Price" : 900},
];

console.log(getCheapest(data, "iphone xs"));

【讨论】:

  • 很高兴听到。不客气
猜你喜欢
  • 2012-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多