gpt4 book ai didi

javascript - 数组缩减未返回预期结果

转载 作者:行者123 更新时间:2023-11-28 17:15:22 25 4
gpt4 key购买 nike

我正在开发一个搜索函数,该函数通过数组过滤器传递,然后进行缩减以将正确的字符串相互匹配,但在获得预期结果方面遇到了一些困难。

我有一个常用短语的枚举,我想将其映射到它们的值,例如,如果搜索 Amer,它也应该匹配 American。为了实现这一目标,我设置了一个带有一些值的对象,该对象应该将值添加到搜索字符串中,例如,如果 API 数据或搜索数据包含 U Street African Amer 它应该在返回中将其转换为u street african amer american。如果它没有找到任何映射数据,它应该传回原始函数参数。

const acronymEnum = {
MT: 'Mountain',
AMER: 'American',
PL: 'Place',
UDC: 'Univeristy of the District of Columbia',
AU: 'American University',
AVE: 'Avenue',
CUA: 'Catholic University of America',
NOMA: 'North of Massechusets Avenue',
GMU: 'George Mason University',
VT: 'Virginia Tech',
UVA: 'University of Virginia',
RAEGAN: 'DCA',
ST: 'Street',
SW: 'South West',
SQ: 'Square',
PENN: 'Pennsylvania',
};

function convertStationAcronym(stationName) {
return Object.keys(acronymEnum).reduce((previous, current) => {
if (stationName.toLowerCase().includes(current.toLowerCase())) {
console.log('trigger the match', current)
return stationName.concat(` ${acronymEnum[current]}`).toLowerCase();
} else {
return previous.toLowerCase();
}
}, '');
}

console.log(convertStationAcronym('U Street African Amer'))

我遇到的问题是,它要么返回未定义,要么根据传递到函数中的内容仅向返回值添加一个映射短语。任何帮助,将不胜感激!

最佳答案

您需要以 stationName 作为初始值启动 reduce,然后始终连接到 previous 而不是原始 stationName 值:

const acronymEnum = {
MT: 'Mountain',
AMER: 'American',
PL: 'Place',
UDC: 'Univeristy of the District of Columbia',
AU: 'American University',
AVE: 'Avenue',
CUA: 'Catholic University of America',
NOMA: 'North of Massechusets Avenue',
GMU: 'George Mason University',
VT: 'Virginia Tech',
UVA: 'University of Virginia',
RAEGAN: 'DCA',
ST: 'Street',
SW: 'South West',
SQ: 'Square',
PENN: 'Pennsylvania',
};

function convertStationAcronym(stationName) {
return Object.keys(acronymEnum).reduce((previous, currentKey) => {
const re = new RegExp("\\b" + currentKey + "\\b", "i"); // TODO: escape special characters
if (re.test(stationName)) {
console.log('trigger the match', currentKey)
return previous.concat(' ', acronymEnum[currentKey]);
// ^^^^^^^^
} else {
return previous;
}
}, stationName).toLowerCase();
// ^^^^^^^^^^^
}

console.log(convertStationAcronym('U Street African Amer'))

关于javascript - 数组缩减未返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581189/

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