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:

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.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join