w3resource

JavaScript: Apply a function against an accumulator and each key in the object

JavaScript fundamental (ES6 Syntax): Exercise-118 with Solution

Write a JavaScript program to apply a function against an accumulator and each key in the object (from left to right).

  • Use Object.keys() to iterate over each key in the object.
  • Use Array.prototype.reduce() to apply the specified function against the given accumulator.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
console.log(transform(
  { a: 1, b: 2, c: 1 },
  (r, v, k) => {
    (r[v] || (r[v] = [])).push(k);
    return r;
  },
  {}
));

Sample Output:

{"1":["a","c"],"2":["b"]}

Flowchart:

flowchart: Apply a function against an accumulator and each key in the object

Live Demo:

See the Pen javascript-basic-exercise-118-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to truncate a string up to a specified length.
Next: Write a JavaScript program to create tomorrow's date in a string representation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.