I have an object with keys and values. Each value is an array that describes the position of key in the string.
const input = {
' ': [5],
d: [10],
e: [1],
H: [0],
l: [2,3,9],
o: [4,7],
r: [8],
w: [6],
};
const buildString = (m) => {
}
I heed to return the string Hello world . My solution is shown below:
const buildString = (m) => {
let res = [];
for(let key in m) {
m[key].map(el => {
res[el] = key;
})
}
return res.join('');
}
But I suppose that it can be solved using reduce method. Could someone help me with implementation please? Thanks in advance.
There you go
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);
Reduce doesnt make things simpler everytime, but anyway:
const input = {
' ': [5],
d: [10],
e: [1],
H: [0],
l: [2,3,9],
o: [4,7],
r: [8],
w: [6],
};
const result = Object.entries(input).reduce((word, entry) => {
const [letter, indices] = entry;
for (const index of indices) {
word[index] = letter;
}
return word;
}, []).join('');
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With