我想遍历 react.js 中的一组对象并按条件对其进行排序

时间:2021-08-01 22:36:29

标签: javascript arrays json

我的 JSON 文件看起来像这样

 {
    "PlanetIdentifier": "KOI-1843.03",
    "TypeFlag": 0,
    "PlanetaryMassJpt": 0.0014,
    "RadiusJpt": 0.054,
    "PeriodDays": 0.1768913,
    "SemiMajorAxisAU": 0.0048,
    "Eccentricity": "",
    "PeriastronDeg": "",
    "LongitudeDeg": "",
    "DiscoveryYear": 2012,
    "
  },
  {
    "PlanetIdentifier": "KOI-1843.01",
    "TypeFlag": 0,
    "PlanetaryMassJpt": "",
    "RadiusJpt": 0.114,
    "PeriodDays": 4.194525,
    "SemiMajorAxisAU": 0.039,
    "Eccentricity": "",
    "PeriastronDeg": "",
    "LongitudeDeg": "",
    "DiscoveryYear": "",
  }

现在我的目标是按 year 对对象进行排序,然后使用 RaduisJpt 再次对其进行排序。

if(RaduisJpt > 2) then it is large planet
if(RaDuisJpt <1) then it is a small planet
else it is a medium

然后我必须展示每年有多少小、中和大行星被发现。

1 个答案:

答案 0 :(得分:0)

使用Array#sort

const arr = [{
    "PlanetIdentifier": "KOI-1843.03",
    "TypeFlag": 0,
    "PlanetaryMassJpt": 0.0014,
    "RadiusJpt": 0.054,
    "PeriodDays": 0.1768913,
    "SemiMajorAxisAU": 0.0048,
    "Eccentricity": "",
    "PeriastronDeg": "",
    "LongitudeDeg": "",
    "DiscoveryYear": 2012,
  },
  {
    "PlanetIdentifier": "KOI-1843.01",
    "TypeFlag": 0,
    "PlanetaryMassJpt": "",
    "RadiusJpt": 0.114,
    "PeriodDays": 4.194525,
    "SemiMajorAxisAU": 0.039,
    "Eccentricity": "",
    "PeriastronDeg": "",
    "LongitudeDeg": "",
    "DiscoveryYear": 2010,
  },
    {
    "PlanetIdentifier": "KOI-1843.01",
    "TypeFlag": 0,
    "PlanetaryMassJpt": "",
    "RadiusJpt": 0.5,
    "PeriodDays": 4.194525,
    "SemiMajorAxisAU": 0.039,
    "Eccentricity": "",
    "PeriastronDeg": "",
    "LongitudeDeg": "",
    "DiscoveryYear": 2010,
  }
]
const sorted = arr.sort((a, b) => {
  let sum = a.DiscoveryYear - b.DiscoveryYear;
  return sum == 0 ? a.RadiusJpt - b.RadiusJpt : sum
})
console.log(sorted);