Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build the string from object keys

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.

like image 639
Dima Kruhlyi Avatar asked Nov 24 '25 11:11

Dima Kruhlyi


2 Answers

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);
like image 168
KooiInc Avatar answered Nov 26 '25 01:11

KooiInc


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);
like image 22
MorKadosh Avatar answered Nov 26 '25 00:11

MorKadosh