如何将Array.some方法匹配到的对应值加入最终输出结果
实现方案
你可以把Array.some()替换为Array.find(),直接获取匹配到的非缩写短语,存在匹配值时再组装成对象推入结果数组即可。
修改后的代码如下:
const sentences = ['i do not', "aren't you"] const result = sentences.reduce((result, sentence) => { const noncontractions = ['do not', 'are not'] // 用find获取匹配到的非缩写短语,无匹配时返回undefined const matchedNoncontraction = noncontractions.find(noncontraction => sentence.includes(noncontraction)) if (matchedNoncontraction) { // 组装为要求的对象格式推入结果 result.push({ sentence: sentence, noncontraction: matchedNoncontraction }) } return result }, []) console.log(result) // 输出:[{ sentence: 'i do not', noncontraction: 'do not'}]
逻辑说明
Array.some()仅返回布尔值表示是否有匹配项,不会返回具体的匹配内容,而Array.find()会返回第一个符合条件的元素,刚好可以拿到你需要的noncontraction值。如果存在单个句子匹配多个非缩写短语的需求,可以把find换成filter,再遍历匹配结果逐个推入对象即可。
内容的提问来源于stack exchange,提问作者wyc
相关产品推荐
相关产品推荐

