我有一个带有键和值的对象。每个值都是一个数组,用于描述键在字符串中的位置。
const input = {
' ': [5],
d: [10],
e: [1],
H: [0],
l: [2,3,9],
o: [4,7],
r: [8],
w: [6],
};
const buildString = (m) => {
}
我注意返回字符串 Hello world 。我的解决方案如下所示:const buildString = (m) => {
let res = [];
for(let key in m) {
m[key].map(el => {
res[el] = key;
})
}
return res.join('');
}
但我想可以使用 解决它减少 方法。有人可以帮我实现吗?提前致谢。
最佳答案
你去吧
const input = {
' ': [5],
d: [10],
e: [1],
H: [0],
l: [2,3,9],
o: [4,7],
r: [8],
w: [6],
};
const words = Object.entries(input)
.reduce( (acc, [character, positions]) => {
// | ^ Object.entries gives you an array of [key, value] arrays
// ^ acc[umulator] is the array (second parameter of reduce)
positions.forEach(v => acc[v] = character);
// ^ put [character] @ the given [positions] within acc
return acc;
}, [])
.join("");
// ^ join the result to make it a a string
console.log(words);
关于javascript - 从对象键构建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66368016/