Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vinothbabu/3314253 to your computer and use it in GitHub Desktop.
Save vinothbabu/3314253 to your computer and use it in GitHub Desktop.
searchable and sortable data structure - Using NodeJS
//sortable-2d-array.js
exports = module.exports = sortable2DArray;
function sortable2DArray(data) {
this.data = data;
}
sortable2DArray.prototype.sortBy = function (o) {
var fields = o.fields || [];
var dir = o.dir || [];
var dataCopy = this.data.slice(0);
if (!fields.length) {
return dataCopy;
}
var sortOptions = [];
for (var i = 0, tmp; i < fields.length; i++) {
if (typeof fields[i] == "undefined") continue;
var tmp = (typeof dir[i] == "undefined") ? "asc" : dir[i];
tmp = "" + tmp;
tmp = tmp.toLowerCase();
if (tmp == "desc" || tmp == "descending") {
sortOptions.push(["" + fields[i], "desc"]);
continue;
}
sortOptions.push(["" + fields[i], "asc"]);
}
if (!sortOptions.length) {
return dataCopy;
}
//note that sort directly edits the array so we are working on a copy
dataCopy.sort(function (itemA, itemB) {
for (var i = 0, a, b, dir, c; i < sortOptions.length; i++) {
a = itemA[sortOptions[i][0]];
b = itemB[sortOptions[i][0]];
dir = sortOptions[i][1];
if (typeof a == "number") {
c = (dir == "asc") ? a - b : b - a;
if (c > 0) return 1;
if (c < 0) return -1;
continue;
} else if (typeof a == "string") {
if (dir == "asc") {
if (a > b) return 1;
if (b > a) return -1;
continue;
} else {
if (b > a) return 1;
if (a > b) return -1;
continue;
}
} else {
continue;
}
}
return 0;
});
return dataCopy;
}
//var data=d.sortBy({fields:["name","age"],dir:["asc","desc"]});
var data = new Array(5);
data[0] = {
name: "Nandan Argulkar",
age: 28,
gender: "male"
};
data[1] = {
name: "Mani",
age: 25,
gender: "male"
};
data[2] = {
name: "Priya",
age: 31,
gender: "female"
};
data[3] = {
name: "Nandini",
age: 19,
gender: "female"
};
data[4] = {
name: "Kevin",
age: 20,
gender: "male"
};
alert(data.toSource());
var d = new sortable2DArray(data);
var result = d.sortBy({
fields: ["name", "age"],
dir: ["asc", "desc"]
});
alert(result.toSource());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment