I am having a problem with javascript's reduce() function; 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.
function my_func (param)
{
return param.reduce ( (returnObj, arr) => {
returnObj[arr.charAt(0)] = (new Array(returnObj[arr.charAt(0)].valueOf().push(arr)));
return returnObj;
} , {})
}
groupByfunction like :_.groupBy( ["Here", "is", "a", "sentence", "with", "a", "lot", "of", "words"], v => v.charAt(0).toLowerCase() );