Skip to content

Instantly share code, notes, and snippets.

@ASteinheiser
Created February 16, 2018 18:27
Show Gist options
  • Save ASteinheiser/60fdf09f4981b358399bdacea3dfa4c7 to your computer and use it in GitHub Desktop.
Save ASteinheiser/60fdf09f4981b358399bdacea3dfa4c7 to your computer and use it in GitHub Desktop.
simple array sorting, filtering, searching
console.log(data)
var filterBy
// filtering
switch (body.orderBy.toLowerCase()) {
case 'name':
filterBy = 'first_name'
break;
case 'age':
filterBy = 'age'
break;
case 'jobs':
filterBy = 'jobs'
break;
case 'location':
filterBy = 'location'
break;
case 'email':
filterBy = 'email'
break;
case 'registered':
filterBy = 'created_at'
break;
default:
break;
}
// ordering
if (body.order === 'asc') {
data.Items = data.Items.sort(function(a, b) {
var x = a[filterBy];
var y = b[filterBy];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
console.log('data after sort: ', data)
}
else if (body.order === 'desc') {
data.Items = data.Items.sort(function(a, b) {
var x = b[filterBy];
var y = a[filterBy];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
console.log('data after sort: ', data)
}
// searching
if (body.search) {
const SEARCHABLE_KEYS = ['location', 'first_name', 'last_name', 'email']
let searchFor = body.search.toLowerCase()
console.log('searching for: ', searchFor)
let foundItems = []
for (var i = 0; i < data.Items.length; i++) {
for (var key in data.Items[i]) {
// if the key is searchable AND the item is found AND the user is not in foundItems
if ((SEARCHABLE_KEYS.indexOf(key.toLowerCase()) >= 0) &&
(String(data.Items[i][key]).toLowerCase().includes(searchFor)) &&
(!foundItems.includes(data.Items[i]))) {
console.log('adding: ', data.Items[i])
foundItems.push(data.Items[i])
}
}
}
data.Items = foundItems
}
let totalItemsReturned = data.Items.length
// pagination
if ((body.page || body.page === 0) && body.count) {
let { page, count } = body
let paginatedData = data.Items.slice(count * page, (count * page) + count)
console.log('returning users: ', paginatedData)
response.body = JSON.stringify({ users: paginatedData, totalCount: totalItemsReturned })
context.done(null, response);
}
else {
// no pagination
console.log('returning users: ', data.Items)
response.body = JSON.stringify({ users: data.Items, totalCount: totalItemsReturned })
context.done(null, response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment