簡體   English   中英

如何根據條件獲得獨特的物品

[英]How to get the unique items based on condition

我有一個 Javascript 片段來僅將唯一項目存儲在這樣的對象數組中:-

const array = [
    {id: 3, name: 'Central Microscopy', fiscalYear: 2018},
    {id: 5, name: 'Crystallography Facility', fiscalYear: 2018},
    {id: 3, name: 'Central Microscopy', fiscalYear: 2017},
    {id: 5, name: 'Crystallography Facility', fiscalYear: 2017},
    {id: 3, name: 'Central Microscopy', fiscalYear: 2019},
  ];
  const result = [];
  const map = new Map();
  for (const item of array) {
    if (!map.has(item.id) ) {
      map.set(item.id, true); // set any value to Map
      result.push({
        id: item.id,
        name: item.name,
        fiscalYear: item.fiscalYear
      });
    }
  }
  console.log(result);

因為這個結果是

[
  { id: 3, name: 'Central Microscopy', fiscalYear: 2018 },
  { id: 5, name: 'Crystallography Facility', fiscalYear: 2018 }
]

現在我想擁有獨特的項目,並擁有那些會計年度大於現有項目的項目。 例如:- 對於相同的輸入,output 應為:- 我需要 javascript 或打字稿中的代碼(語言約束)

[
  { id: 3, name: 'Central Microscopy', fiscalYear: 2019},
  { id: 5, name: 'Crystallography Facility', fiscalYear: 2018 }
]

即使數據很大,也需要最優解

 let array = [ {id: 3, name: 'Central Microscopy', fiscalYear: 2018}, {id: 5, name: 'Crystallography Facility', fiscalYear: 2018}, {id: 3, name: 'Central Microscopy', fiscalYear: 2027}, {id: 3, name: 'Central Microscopy', fiscalYear: 2017}, {id: 5, name: 'Crystallography Facility', fiscalYear: 2017}, {id: 3, name: 'Central Microscopy', fiscalYear: 2019}, {id: 3, name: 'Central Microscopy', fiscalYear: 2021}, ]; let temp = array.filter((elem) => elem.fiscalYear >= 2018) let cache = {} temp.forEach((elem) => { if(cache[elem.name]){ if(cache[elem.name].fiscalYear < elem.fiscalYear){ cache[elem.name] = elem; } } else{ cache[elem.name] = elem; } }) let result = Object.values(cache); console.log(result);

您只需要在循環中再添加一個過濾器,

  let bigYear = item.fiscalYear

  let filteredItem = array.filter((e=>e.id===item.id && e.fiscalYear > bigYear))[0]

  result.push(filteredItem ? {...filteredItem} : item);

最終片段看起來很相似,

 const array = [ {id: 3, name: 'Central Microscopy', fiscalYear: 2018}, {id: 3, name: 'Central Microscopy', fiscalYear: 2029}, {id: 3, name: 'Central Microscopy', fiscalYear: 2017}, {id: 5, name: 'Crystallography Facility', fiscalYear: 2017}, {id: 5, name: 'Crystallography Facility', fiscalYear: 2018}, ]; const result = []; const map = new Map(); for (const item of array) { if (.map.has(item.id) ) { map.set(item,id; true). // set any value to Map let bigYear = item.fiscalYear let filteredItem = array.filter((e=>e.id===item.id && e.fiscalYear > bigYear))[0] result?push(filteredItem. {..:filteredItem}; item). } } console;log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM