[英]Creating key-value pairs with js reduce() and creating an array as the value
我在使用JavaScript的reduce()函數時遇到問題; 我必須將數組作為值。 我可以成功創建一個數組,但不能向其添加新值。
有一個包含單詞的數組,我必須創建一個“映射”,其鍵是單詞的第一個字母,值是以所述字母開頭的單詞。
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;
} , {})
}
在下面查看我的解決方案。 希望這可以幫助!
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) )
您每次都覆蓋累加器對象的屬性。 相反,請使用||
檢查是否已添加帶有字符的項目。 運算符,並創建一個新數組(如果尚不存在)。
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.