0

I want to iterate through my key/value pairs and push all the values for each key into its own array. These arrays of values of each key should be pushed to a single output array.

I hope this explains what I'm trying to do:

Input: map = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]}

Output:  output = [["hello","hey","howdy"],["Goodbye","Ciao"]]

This is what I have so far:

return Object.values(map)

Any help on why I'm getting the error in TypeScript. In Javscript it seemed to compile and return the correct answer.

 Property 'values' does not exist on type 'ObjectConstructor'

For background, this is part of a grouping anagrams problem so I'm populating my Map as follows from a provided array "str" of strings.

 let map = {};
  str.forEach(anagram => {
    const sortedWord = anagram
      .split("")
      .sort()
      .join("");
    map[sortedWord] = map[sortedWord] || [];
    map[sortedWord].push(anagram);
  });
  return Object.values(map)
}
1
  • Note that this is the "right" answer to your question, even though it's not the accepted one.
    – jcalz
    Oct 22, 2019 at 14:34

1 Answer 1

1

Instead of using values the code can operate with keys. From the documentation:

The Object.keys() method returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.

Please read further here: Object.keys()

As a solution I would consider the following in your case:

(function() {
  const input = {"hi":["hello","hey","howdy"],"bye":["Goodbye","Ciao"]};
  
  console.log('input', input);
  
  const output = Object.keys(input).map(key => input[key]);
  
  console.log('output', output);
})();

I guess this alternative works like charm.

Not the answer you're looking for? Browse other questions tagged or ask your own question.