Skip to content

Instantly share code, notes, and snippets.

@danieluhl
Created September 11, 2017 14:01
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 danieluhl/a4976900bb5aa4159fac8f50b088363c to your computer and use it in GitHub Desktop.
Save danieluhl/a4976900bb5aa4159fac8f50b088363c to your computer and use it in GitHub Desktop.
Implementing simple array sorting from scratch
const customers = [{
name: 'Billy',
age: 32,
averageOrderValue: '$34.38'
}, {
name: 'Mike',
age: 23,
averageOrderValue: '$300.38'
}, {
name: 'Zac',
age: 42,
averageOrderValue: '$43.38'
}, {
name: 'Jayne',
age: 45,
averageOrderValue: '$199.38'
}];
const bubble = (arr, compare) => {
for (let i = arr.length - 1; i > 0; i--) {
for (let j = 0; j < i; j++) {
// if current < next: swap
if (compare(arr[j], arr[j + 1]) > 0) {
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
const createCompareByProperty = property => (a, b) => a[property] > b[property] ? 1 : -1;
const compareCustomersByName = createCompareByProperty('name');
const compareCustomersByAge = createCompareByProperty('age');
const compareCustomersByAOV = (a, b) => {
const aAOV = parseFloat(a.averageOrderValue.substring(1));
const bAOV = parseFloat(b.averageOrderValue.substring(1));
return aAOV > bAOV ? 1 : -1;
}
const sorted = bubble(customers, compareCustomersByAOV);
sorted;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment