gpt4 book ai didi

JavaScript 查找字符串的 "newest"版本

转载 作者:行者123 更新时间:2023-11-30 11:19:56 25 4
gpt4 key购买 nike

这可能真的很简单,但我想不出任何好的解决方案:

我有一个字符串数组:

let array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];

及时这个数组会改变,但在任何时候我都希望能够将该数组减少到字符串的“最新”版本(基于结尾数字,它们有时可能变成 2 位或 3 位数字点),所以我最终想要的是:

['House3', 'Block2', 'BlockSpecial1']

最佳答案

Reduce数组到一个以字符串为键、版本为值的对象。要获取字符串和版本,您可以使用 String.match() , 和 array destructuring .然后使用 Object.entries() , 和 Array.map()将它组合回字符串:

const array = ['House1', 'House2', 'House3', 'Block1', 'Block2', 'BlockSpecial1'];

const result = Object.entries(array.reduce((r, s) => {
const [, str, version] = s.match(/([A-Za-z]+)(\d+)/);

r[str] = (r[str] || 0) > version ? r[str] : version; // or r[str] = version if the versions are always in the right order

return r;
}, Object.create(null)))
.map(([k, v]) => k + v);

console.log(result);

关于JavaScript 查找字符串的 "newest"版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192234/

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