w3resource

JavaScript: Reduce a given Array-like into a value hash

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

Reduce Array-Like to Hash Map

Write a JavaScript program to reduce a given Array-like into a value hash (keyed data store).

Note: Given an Iterable or Array-like structure, call Array.prototype.reduce.call() on the provided object to step over it and return an Object, keyed by the reference value.

  • Given an iterable object or array-like structure, call Array.prototype.reduce.call() on the provided object to step over it and return an Object, keyed by the reference value.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 

// Define the 'toHash' function.
const toHash = (object, key) =>
  Array.prototype.reduce.call(
    object,
    (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc),
    {}
  );

// Test the 'toHash' function with sample inputs.
toHash([4, 3, 2, 1]); 
toHash([{ a: 'label' }], 'a'); 

// A more in-depth example
let users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];
let managers = [{ manager: 1, employees: [2, 3] }];
managers.forEach(
  manager =>
    (manager.employees = manager.employees.map(function(id) {
      return this[id];
    }, toHash(users, 'id')))
);

// Output the result.
console.log(managers); // Output: [ { manager: 1, employees: [ { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' } ] } ]

Output:

[{"manager":1,"employees":[{"id":2,"first":"Joe"},{"id":3,"first":"Moe"}]}]

Flowchart:

flowchart: Reduce a given Array-like into a value hash

Live Demo:

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


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to convert a string to kebab case.
Next: Write a JavaScript program to convert a float-point arithmetic to the Decimal mark form and It will make a comma separated string from a number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-124.php