[英]Creating key-value pairs with js reduce() and creating an array as the value
I am having a problem with javascript's reduce() function; 我在使用JavaScript的reduce()函数时遇到问题; I have to put arrays as the value.
我必须将数组作为值。 I can sucessfully create an array but can't add new values to it.
我可以成功创建一个数组,但不能向其添加新值。
There's an array with words and I have to create a 'map' whose keys are the first letters of the words and the values are the words which start with the said letter. 有一个包含单词的数组,我必须创建一个“映射”,其键是单词的第一个字母,值是以所述字母开头的单词。
arr = ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"];
The expected output should be this: 预期的输出应为:
{ h: [ "here" ],
i: [ "is" ],
a: [ "a", "a" ],
s: [ "sentence", ],
w: [ "with", "words" ],
l: [ "lot" ],
o: [ "of" ]
}
This is my solution to the problem but it overwrites existing values. 这是我对问题的解决方案,但它会覆盖现有值。
function my_func (param)
{
return param.reduce ( (returnObj, arr) => {
returnObj[arr.charAt(0)] = new Array(push(arr));
return returnObj;
} , {})
}
I tried this but it didn't work because it couldn't deduce the type for valueOf() and it yielded an error. 我尝试了此操作,但由于无法推断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;
} , {})
}
Check out my solution below. 在下面查看我的解决方案。 Hope this helps!
希望这可以帮助!
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) )
You are overwriting the accumulator object's property every time. 您每次都覆盖累加器对象的属性。 Instead, check if an item with the character has already been added using the
||
相反,请使用
||
检查是否已添加带有字符的项目。 operator and create a new array if it doesn't exist yet. 运算符,并创建一个新数组(如果尚不存在)。
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))
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 );
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
}, {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.