从对象键构建字符串

Build the string from object keys

我有一个包含键和值的对象。每个值都是一个数组,描述了键在字符串中的位置。

 const input = {
  ' ': [5],
  d: [10],
  e: [1],
  H: [0],
  l: [2,3,9],
  o: [4,7],
  r: [8],
  w: [6],
};

const buildString = (m) => {
 
}

我注意到 return 字符串 Hello world 。我的解决方案如下所示:

const buildString = (m) => {
  let res = [];
  for(let key in m) {
    m[key].map(el => {
      res[el] = key;
    })
  }
  return res.join('');
}

不过我想可以用reduce的方法解决。有人可以帮我实施吗? 提前致谢。

好了

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);

您需要采用双重嵌套循环,一个用于迭代条目,另一个用于获取索引。

为了收集字符,您需要一个数组和 return 连接的数组。

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));

可能可以做得更好,但这是我的尝试。

它使用 Object.entriesinput“转换”为 key/value 数组对的数组。

然后循环遍历每个条目及其位置,并将它们放在累加器数组中的正确位置。

最后,它使用数组方法join将累加器数组转换为字符串。

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))

减少并不能每次都让事情变得更简单,但无论如何:

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);