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



我在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;
  } , {})
}

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

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

在下面查看我的解决方案。希望这有帮助!

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

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
}, {})

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

最新更新