Challenge

by jacobwsmith

HTML

<h1>
Challenge
</h1>
<h3>
  Part 1: Formatted Array to Object of Indexes
</h3>
<div id="test1">Loading...</div>

<h3>
  Part 2: Formatted Unique Sorted Array to String
 </h3>
<div id="test2">Loading...</div>

JavaScript

'use strict';	

/*
*	Formats a string by lowercasing all characters expect the first letter in the word
*
*	@param {string} str
*	@return {string}
*
*	Note: see Array.map
*/
function capitalizeFirstLetter(str) {
  return str.toLowerCase().charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}

/*
*	Creates an object from an array. object keys equal the array values and 
*	object value is an array of the array indexes
* 
*	@param {object} previousValue - initial object
* @param {string} currentValue
* @param {number} currentIndex
*	@return {object} previousValue - and returned
*
*	Note: see Array.reduce
*/
function arrayToObjectOfIndexes(previousValue, currentValue, currentIndex) {
  if (Array.isArray(previousValue[currentValue])) {
    previousValue[currentValue].push(currentIndex);
  } else {
    previousValue[currentValue] = [currentIndex];
  }
  return previousValue;
};

/*
* Returns a unique array
*
* @param {array} previousValue - inital value
* @param {string} currentValue
* @return {array} previousValue - and the returned value
*
* Note: see Array.reduce
*/
function uniqueArray(previousValue, currentValue) {
  // Note: you could put format functionality here to optimize performance
  if (previousValue.indexOf(currentValue) < 0) {
    // Note: you could put sort functionality here to optimize performance
    previousValue.push(currentValue);
  }
  return previousValue;
}

//////

// Testing in IFFE (Immediately-invoked function expression) so we don't pollute global name space
(function(){

	/*
  * Array for testing
  */
	var arr = ['Nick', 'jake', 'RAY', 'Kate', 'Nick', 'Jeremy', 'nick', 'AMOL', 'rAY', 'VIANNEY', 'Shilpika', 'nick', 'THOMAS', 'tom', 'james', 'JERM', 'amOl', 'kate'];

	/*
  * Test Part 1
  */
  var test1 = arr
    .map(capitalizeFirstLetter)
    .reduce(arrayToObjectOfIndexes, {});
  test1 = JSON.stringify(test1);
  console.log('=== Test 1 ===');
  console.log(test1);
  document.getElementById('test1').innerHTML = test1;

	/*
  * Test part...