JSFiddle - React, Tailwind, and code Playground
JavaScript
// Data Layer
// -------------------------------------------
var dataNoSort = [{
shape: "square",
color: "yellow",
height: "20px",
width: "40px"
}, {
shape: "circle",
color: "yellow",
height: "200px",
width: "100px"
}, {
shape: "square",
color: "blue",
height: "40px",
width: "20px"
}, {
shape: "circle",
color: "yellow",
height: "200px",
width: "100px"
}];
console.log('unsorted', dataNoSort);
var data = [{
shape: "square",
color: "yellow",
height: "20px",
width: "40px"
}, {
shape: "circle",
color: "yellow",
height: "200px",
width: "100px"
}, {
shape: "square",
color: "blue",
height: "40px",
width: "20px"
}, {
shape: "circle",
color: "yellow",
height: "200px",
width: "100px"
}];
console.log('sorted', data);
// -------------------------------------------
// Define
// -------------------------------------------
function sortByCriteria(data, criteria) {
return data.sort(function (a, b) {
var i, iLen, aChain, bChain;
i = 0;
iLen = criteria.length;
for (i; i < iLen; i++) {
aChain += a[criteria[i]];
bChain += b[criteria[i]];
}
return aChain.localeCompare(bChain);
});
}
// -------------------------------------------
// Invoke (criteria ordered by importance)
// -------------------------------------------
sortByCriteria(data, ["shape", "color", "height", "width"]);
// -------------------------------------------