gpt4 book ai didi

javascript - 对年份数组进行排序(包括 BCE)

转载 作者:行者123 更新时间:2023-12-05 01:58:11 24 4
gpt4 key购买 nike

有一个包含化学元素及其发现年份的对象数组:

[
{"name": "hydrogen", "discovered": "1766"},
{"name": "boron", "discovered": "1808"},
{"name": "copper", "discovered": "9000 BCE"},
{"name": "argon", "discovered": "1894"},
{"name": "iron", "discovered": "before 5000 BCE"},
{"name": "phosphorus", "discovered": "1669"}
]

我想要的是根据发现的年份对数组进行排序,因此最古老的(在本例中为铜)应该是第一项,最近的(氩)应该是最后一项。

//It should look like this in the end:
[
{"name": "copper", "discovered": "9000 BCE"},
{"name": "iron", "discovered": "before 5000 BCE"},
{"name": "phosphorus", "discovered": "1669"},
{"name": "hydrogen", "discovered": "1766"},
{"name": "boron", "discovered": "1808"},
{"name": "argon", "discovered": "1894"}
]

我遇到的问题是“before”、“BCE”、“CE”等几个关键字,我不知道如何处理。

有什么解决方案可以解决这个问题吗?

最佳答案

9000 BCE-9000 年相同。

您可以简单地将那些 BCE(关键字 before 可能会被忽略,因为它无论如何都包含 BCE)数据字符串视为 - sort函数中的年份,如下:

const data = [{name:"hydrogen",discovered:"1766"},{name:"boron",discovered:"1808"},{name:"copper",discovered:"9000 BCE"},{name:"argon",discovered:"1894"},{name:"iron",discovered:"before 5000 BCE"},{name:"phosphorus",discovered:"1669"}];

const res = data.sort((a, b) => {
const numA = (a.discovered.includes("BCE") ? -1 : 1)
* a.discovered.replace(/\D/g, '')
const numB = (b.discovered.includes("BCE") ? -1 : 1)
* b.discovered.replace(/\D/g, '')
return numA - numB
})

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

关于javascript - 对年份数组进行排序(包括 BCE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68677916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com