使用js reduce()创建键值对并创建数组作为值

问题描述 投票:1回答:4

我有javascript reduce()函数的问题;我必须将数组作为值。我可以成功创建一个数组但不能为其添加新值。

有一个带有单词的数组,我必须创建一个'map',其键是单词的第一个字母,值是以所述字母开头的单词。

arr = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"];

预期的输出应该是这样的:

{ ​h: [ "here" ],
  ​i: [ "is" ],
  ​a: [ "a", "a" ],
  ​s: [ "sentence", ]​,
  w: [ "with", "words" ]​,
  l: [ "lot" ],
  ​o: [ "of" ]
}

这是我对问题的解决方案,但它会覆盖现有值。

function my_func (param)
{
   return param.reduce ( (returnObj, arr) => {
    returnObj[arr.charAt(0)] = new Array(push(arr));
    return returnObj;
  } , {})

}

我尝试了这个,但它不起作用,因为它无法推断valueOf()的类型,它产生了一个错误。


function my_func (param)
{
   return param.reduce ( (returnObj, arr) => {
    returnObj[arr.charAt(0)] = (new Array(returnObj[arr.charAt(0)].valueOf().push(arr)));
    return returnObj;
  } , {})

}
javascript arrays reduce
4个回答
0
投票

您每次都要覆盖累加器对象的属性。相反,检查是否已使用||运算符添加了具有该字符的项目,如果尚不存在则创建新数组。

let array = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"]

function my_func(param) {
  return param.reduce((acc, str) => {
    let char = str.charAt(0).toLowerCase();
    acc[char] = acc[char] || [];
    acc[char].push(str.toLowerCase());
    return acc;
  }, {})
}

console.log(my_func(array))

0
投票

看看我的解决方案如下。希望这可以帮助!

const arr = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"];

const getWordsDict = (array) => array.reduce(
  (acc, word) => {
    const lowerCasedWord = word.toLowerCase()
    const wordIndex = lowerCasedWord.charAt(0)

    return {
      ...acc,
      [wordIndex]: [
        ...(acc[wordIndex] || []),
        lowerCasedWord,
      ],
    }
  }, 
  {}
)

console.log( getWordsDict(arr) )

0
投票
param.reduce((acc, el) => {
  const key = el[0] // use `el[0].toLowerCase()` for case-insensitive 
  if (acc.hasOwnProperty(key)) acc[key].push(el)
  else acc[key] = [el]
  return acc
}, {})

0
投票

var result = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"].reduce(function(map, value) {

  var groupKey = value.charAt(0).toLowerCase();
  var newValue = value.toLowerCase();

  return map[groupKey] = map.hasOwnProperty(groupKey) ? map[groupKey].concat(newValue) : [newValue], map;
}, {});

console.log( result );
© www.soinside.com 2019 - 2024. All rights reserved.