DEV Community

Bruce Axtens
Bruce Axtens

Posted on • Updated on

Reversing a string using Object.keys() and .reduce?

We all use Object.keys() to get the keys of an object. Standard thing. So what happens when you get the keys of something else? The following is out of Lychen's REPL.

Lychen>let obj = {word:"bravo",translation:"shabaash"}
[undefined]
Lychen>Object.keys(obj).join()
word,translation
Enter fullscreen mode Exit fullscreen mode

Yes, what we'd expect. What about an array?

Lychen>let arr = 'aap ka nam kya hai?'.split(" ")
[undefined]
Lychen>Object.keys(arr).join()
0,1,2,3,4
Enter fullscreen mode Exit fullscreen mode

Hmm ... indices? Probably.

Lychen>const chabian = Object.keys(arr)
[undefined]
Lychen>arr[chabian[3]]
kya
Enter fullscreen mode Exit fullscreen mode

Definitely.

Okay, what about a string?

Lychen>let str = "aap ki tabiyat kaisi hai?"
[undefined]
Lychen>Object.keys(str).join()
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24
Enter fullscreen mode Exit fullscreen mode

That bit of Urdu is 24 characters long. Let's see if it really is indices.

Lychen>const indices = Object.keys(str)
[undefined]
Lychen>str[indices[1]]
a
Lychen>str[indices[2]]
p
Enter fullscreen mode Exit fullscreen mode

Looks like it.

And what about Object.keys of a number?

Lychen>const num = 58
[undefined]
Lychen>Object.keys(num).join()

Lychen>typeof Object.keys(num)
object
Lychen>Object.keys(num) === null
False
Enter fullscreen mode Exit fullscreen mode

Hmm, so whatever the Object.keys of a number is, join returns an empty string, the typeof is object and it's not null.

Lychen>Object.keys(num) instanceof Array
True
Enter fullscreen mode Exit fullscreen mode

Right. An empty array. Makes sense. I think.

So the routine. I'll leave it for others to test (I have and it's not particularly performant):

function Bruce_ObjectKeysReduce(string) {
  return Object.keys(string).reduce(function (acc, cur) {
    acc = string[cur] + acc;
    return acc;
  }, "");
}
Enter fullscreen mode Exit fullscreen mode

(later)

That can be boiled down a little bit more, using ES6 forms, to

const Bruce_ObjectKeysReduce = (string) =>
    Object.keys(string).reduce((acc, cur) => {
      acc = string[cur] + acc;
      return acc;
    }, "");
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
diek profile image
diek

You can reverse sort the first split code you tried, too.

Collapse
 
bugmagnet profile image
Bruce Axtens • Edited

I could but then you'd miss out on the unicorns, love hearts and bookmarks. As enslaved as I am to the praise of my peers ...