Reputation: 59
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.
Upvotes: 3
Views: 1070
Reputation: 122908
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);
Upvotes: 2
Reputation: 6006
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);
Upvotes: 1
Reputation: 4122
Probably could be done better, but here's my attempt.
It uses Object.entries
to "convert" input
into an array of key/value array pairs.
Then it loops through each entry and it's positions and puts them in the correct place in the accumulator array.
Finally, it uses the array method join
to convert the accumulator array to a string.
const input = {
' ': [5],
d: [10],
e: [1],
H: [0],
l: [2, 3, 9],
o: [4, 7],
r: [8],
w: [6],
};
const buildString = (m) => {
return Object.entries(m).reduce((acc, [key, positions], ind) => {
positions.forEach(val => acc[val] = key);
return acc;
}, []).join('');
}
console.log(buildString(input))
Upvotes: 0
Reputation: 386560
You need to take double nested loops, one for iterating the entries and the other to get the index.
For collecting the characters, you need an array and return the joined array.
const
input = { ' ': [5], d: [10], e: [1], H: [0], l: [2, 3, 9], o: [4, 7], r: [8], w: [6] },
buildString = (m) => {
const letters = [];
for (let [character, indices] of Object.entries(m)) {
for (const index of indices) {
letters[index] = character;
}
}
return letters.join('');
};
console.log(buildString(input));
Upvotes: 0