javascript - 你如何使用字典对象来比较 Javascript 中给定数组的键?
问题描述
我正在做一个代码挑战,我想在一串单词中找到“最高值”的单词。我已将“az”字符指定为键,将数字“1-26”指定为对象中的值。我想知道是否有一种方法可以将给定字符串的单词中的字母与我的字典对象进行比较,并开始将字母的值相加以找到“最高值”单词。这是我的字典对象:
let testStr = 'man i need a taxi up to ubud'
testStr.split(' ')
const values = [...Array(27).keys()]
values.shift()
const keys = String.fromCharCode(...[...Array('z'.charCodeAt(0) - 'a'.charCodeAt(0) + 1).keys()]
.map(i => i + 'a'.charCodeAt(0)))
const merged = [...keys].reduce((obj, key, index) => ({ ...obj,
[key]: values[index]
}), {})
console.log(JSON.stringify(merged) + '\n' + testStr)
解决方案
您可以使用map
andreduce
来获取每个单词的值。您也可以将单词的索引与值一起存储,然后将值从最高到最低排序,然后直接使用 [0] 访问最高值,并通过索引 [1] 访问单词。
let testStr = 'man i need a taxi up to ubud'
const values = [...Array(27).keys()]
values.shift()
const keys = String.fromCharCode(...[...Array('z'.charCodeAt(0) - 'a'.charCodeAt(0) + 1).keys()]
.map(i => i + 'a'.charCodeAt(0)))
const merged = [...keys].reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {})
console.log(
testStr.split(' ')
.map(w => [w.split('').reduce((a, l) => (a += merged[l] || 0), 0), w])
.sort(([a], [b]) => b - a)[0][1]
)
然后你可以把它变成一个 util 函数:
const values = [...Array(27).keys()]
values.shift()
const map = [...String.fromCharCode(...[...Array('z'.charCodeAt(0) - 'a'.charCodeAt(0) + 1).keys()]
.map(i => i + 'a'.charCodeAt(0)))].reduce((obj, key, index) => ({ ...obj, [key]: values[index]}), {})
const getHighest = s => (
s.toLowerCase()
.split(' ')
.map((w, i) => [w.split('').reduce((a, l) => (a += map[l] || 0), 0), w])
.sort(([a], [b]) => b - a)[0][1]
)
console.log(getHighest('man i need a taxi up to ubud'))
console.log(getHighest('This is a test'))
但是,在循环期间而不是事先在映射中获取值时,编写起来更容易且更短:
const getHighest = s => (
s.toLowerCase()
.split(' ')
.map((w, i) => [w.split('').reduce((a, l) => (a += l.charCodeAt() || 0), 0), w])
.sort(([a], [b]) => b - a)[0][1]
)
console.log(getHighest('man i need a taxi up to ubud'))
console.log(getHighest('This is a test'))
推荐阅读
- java - 过滤值不区分大小写的字符串集合
- odata - SAP oData 服务 - 如何链接两个实体集
- google-apps-script - 获取过滤结果中的行号
- javascript - Mesibo:React / 创建 React App 集成
- powershell - 包含超过 40.000 个文件的文件夹
- docker - docker-compose 来自文件的参数
- asp.net-mvc - .net mvc SendAsync - 如果无法发送消息,如何查找错误日志?
- google-cloud-platform - Google Cloud Function 与“503 Service Unavailable”消息一起使用
- ios - 将 UIViews 连接到 json 响应,反之亦然
- azure-active-directory - Microsoft Graph:尝试获取邮箱设置时收到 400 错误请求