Unique Sorted Names - Array
by jacobwsmith
JavaScript
/*
Question:
Fictional Problem: We have had various groups at Nielsen manually enter user names. Unfortunately there was no quality control or validation and we have a number of names that are duplicated with no standard on formatting, For example, someone entered both RAY and Ray, even though ray is only one name despite the case.
Task:
The project manager would like a clean, formatted, sorted list of all names. We need a method that will perform this functionality. The results of this method should be output to an html page as well as the console.
*/
const names = ['Nick', 'jake', 'RAY', 'Kate', 'Nick', 'Jeremy', 'Ryan', 'nick', 'AMOL', 'rAY', 'VIANNEY', 'Samuel', 'ryan', 'Shilpika', 'nick', 'THOMAS', 'tom', 'james', 'JERM', 'amOl', 'kate', 'SCOTT', 'Jenifer', 'bill', 'jenny', 'STEVEN', 'Ray'];
/*
===========================================
Solution:
We should ask questions and not assume.
The answers below will impact how one goes about this problem:
- What browsers are we targeting (es2015)?
- What is the expected sort order (Ascending or Descending)?
- What is a duplicate (Ray, RAY, and ray)?
- What is the expected format of the names (Ray, ray, RAY)?
- What is the expected format of the console.log output?
- What is the expected format of the html output?
- Do we need to handle cases outside this data set ('MacGyver', 'Mac Gyver', array size, non-string value, etc...)?
===========================================
*/
// Option 1, using array chaining and perhaps more readable
const uniqueSortedNames = (list) => {
return list
.map(res => res.toUpperCase())
.sort()
.filter((element, index, array) => index === 0 || element !== array[index - 1]);
} {
const result = uniqueSortedNames(names);
console.log('result: ', result);
const element = document.createElement('p');
element.innerHTML = result.join(', ');
document.getElementsByTagName('body')[0].appendChild(element);
}