3

some one gave me this question as a practice problem. I have to use "_.reduce" on the following object to print out the text "a good practice". Quite frankly I am struggling even to visualize this in my head. Any help would be appreciated.

var test = {a:'a',b:{a:'good',c:{c:'practice'}}}

Thank You!

2
  • 2
    Welcome to SO - we're here to help, not do homework. Try to write the solution yourself first, then come back when you get stuck on a specific question. Commented Dec 1, 2016 at 21:17
  • 3
    its not my homework nor is it for any class or challenge. It was simply a practice problem that my friend gave me. And I did tackle it for 48 hours. when everything else failed I head here. Commented Dec 1, 2016 at 21:32

1 Answer 1

3

Because you don't know how nested the object is, you'll need to use recursion to accomplish the task at hand. You can't use .reduce on the object itself, so you'll have to use Object.keys to get an array of properties from the object. Then you can .reduce the returned array.

var test = {a:'a',b:{a:'good',c:{c:'practice'}}};
var deeperTest = {a:'a',b:{a:'deeper',b:{a:'test',b:{a:'than',b:{a:'before'}}}}};

function reducer(obj) {
  if (typeof obj != 'object') return ''; //we only want to reduce 'objects'
  return Object.keys(obj).reduce(function(prev, curr) {
    if (typeof obj[curr] != 'string')
      prev += ' ' + reducer(obj[curr]); //probably an object - let's dig in
    else
      prev += ' ' + obj[curr]; //just a string - append to accumulator
    return prev;
  }, "");  
}

console.log(reducer(test));
console.log(reducer(deeperTest));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.