Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var deepSort = function(arr){
- var i;
- var hasPositionKey = [];
- var noPositionKey = [];
- var nestedObj;
- var positions = [];
- var loggingPositions = {};
- var positionSortedObjects = [];
- // iterate through the array of objects
- for(i = 0; i < arr.length; i++){
- // set a variable for the individual object being considered
- nestedObj = arr[i];
- // if that object has a position of false
- if(nestedObj.position === false){
- // push false object into the array of false position objects
- noPositionKey.push(nestedObj);
- }
- // if the object has a numbered position
- if(typeof nestedObj.position === 'number'){
- // push numbered position to the array of numbered position objects
- hasPositionKey.push(nestedObj);
- }
- }
- // iterate through the array of objects with positions
- for(i = 0; i < hasPositionKey.length; i++){
- // set a variable for the individual object being considered
- nestedObj = hasPositionKey[i];
- // push only the position number into an array to track positions
- positions.push(nestedObj.position);
- // add a key value pair of position:id to an object
- loggingPositions[nestedObj.position] = nestedObj.id;
- }
- // sort the array that stores the positions of the non-false objects
- positions.sort();
- // iterate through that array and construct a final array of objects by sorted position
- for(i = 0; i < positions.length; i++){
- // set a variable for the positions, as encountered in order:
- var num = positions[i];
- // set a key for the object to be constructed
- var key = loggingPositions[num];
- // set a value for the object to be constructed
- var value = num;
- // construct a result object with object literal notation:
- var result = {
- id: key,
- position: value
- };
- // push the constructed objects into the positionSortedObjects array
- positionSortedObjects.push( result );
- }
- // return a concatenated array of the positionSortedObjects + the noPositionKey objects
- return (positionSortedObjects.concat(noPositionKey));
- };
- var sample = [
- {
- id : 1,
- position: false
- },
- {
- id: 2,
- position: false
- },
- {
- id: 3,
- position: 4
- },
- {
- id: 4,
- position: false
- },
- {
- id: 5,
- position: 2
- },
- {
- id: 6,
- position: 5
- },
- {
- id: 7,
- position: 3
- },
- {
- id: 8,
- position: 1
- }
- ];
- deepSort(sample);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement