首页 > 解决方案 > 你如何使用字典对象来比较 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)

标签: javascriptarraysstringdictionaryobject

解决方案


您可以使用mapandreduce来获取每个单词的值。您也可以将单词的索引与值一起存储,然后将值从最高到最低排序,然后直接使用 [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'))


推荐阅读