Skip to content

Instantly share code, notes, and snippets.

@CarlinCanales
Created September 15, 2021 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CarlinCanales/6dd77533645c98a4e91fd3c441aaee5a to your computer and use it in GitHub Desktop.
Save CarlinCanales/6dd77533645c98a4e91fd3c441aaee5a to your computer and use it in GitHub Desktop.
Add and sort
/*
Your previous Plain Text content is preserved below:
Given two arrays:
Array 1 - A distinct set of ice cream flavors
Array 2 - A set of ice cream flavors (may contain duplicates)
Please write a function that returns the values of Array 2 sorted by the order of Array 1.
```jsx
Array 1 - ['vanilla', 'mint', 'chocolate']
Array 2 - [ 'mint', 'vanilla', 'mint', 'chocolate', 'mint', 'chocolate']
Return Value - ['vanilla', 'mint', 'mint', 'mint', 'chocolate', 'chocolate']
```
*/
const arr1 = ['vanilla', 'mint', 'chocolate'];
const arr2 = ['chocolate', 'chocolate', 'chocolate', 'mint', 'mint', 'mint'];
//['vanilla', 'mint', 'mint', 'mint', 'chocolate'];
let sortedFlavors = (distinctFlavors, dupFlavors) => dupFlavors.reduce((sortedFlavors, flavor, index, originalArray) => {
// if current flavor is not current in the sortedFlavors array
if (sortedFlavors.indexOf(flavor) < 0) {
const isThereAflavorAlreadyInArrayAtIndexOfCurrentFlavor = !!sortedFlavors[distinctFlavors.indexOf(flavor)];
if (isThereAflavorAlreadyInArrayAtIndexOfCurrentFlavor) {
const idx = sortedFlavors.lastIndexOf(distinctFlavors.indexOf(flavor));
if (idx === 0) {
sortedFlavors.push(flavor);
} else {
const indexOfPreviousFlavor = sortedFlavors.lastIndexOf(distinctFlavors[distinctFlavors.indexOf(flavor) - 1]);
sortedFlavors.splice(indexOfPreviousFlavor + 1, 0, flavor);
}
} else {
const indexOfFlavor = distinctFlavors.indexOf(flavor);
sortedFlavors[indexOfFlavor] = flavor;
}
} else {
// current flavor is already in the array once so we just need to add this new instance next to that one
const idx = sortedFlavors.lastIndexOf(flavor);
sortedFlavors.splice(idx, 0, flavor);
}
if (index === originalArray.length - 1) {
// this should remove possible empty indexes if, for example, mint or chocolate is not in dupFlavors
const stringWithEmptyRemoved = sortedFlavors.join('-').replace('--', '-');
// this accounts for a beginning '-' if, for example, vanilla is not in dupFlavors
if (stringWithEmptyRemoved[0] === '-') {
return stringWithEmptyRemoved.slice(1).split('-')
}
// turn back into an array
return stringWithEmptyRemoved.split('-');
}
return sortedFlavors
}, []);
console.log(sortedFlavors(arr1, arr2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment