Skip to content
Advertisement

Sort object by array within array?

I have a local storage that looks like this:

Key: Savedme        
Value:
{
 "Bob":["1","1"],
 "John":["2","1"],
 "Mom":["3","1"],
 "Dad":["1","2"],
 "Tom":["3","2"],
 "Skipper42":["2","3"],
 "Hated_41":["3","3"],
 "Greeneggs":["2","2"],
 "William":["1","3"]
}

I need to somehow sort it to look like this

{
 "Bob":["1","1"],
 "Dad":["1","2"],
 "William":["1","3"]
 "John":["2","1"],
 "Greeneggs":["2","2"],
 "Skipper42":["2","3"],
 "Mom":["3","1"],
 "Tom":["3","2"],
 "Hated_41":["3","3"]
}

I’ve tried storing it in a matrix such as this:

var $runthrough = [[]];
$runthrough[$x,$y] = $values;

Where x is the first set of numbers, y is the next and then values is Bob, Dad etc…from there I could just do a foreach for both sections of the matrix and it would be done, HOWEVER when I use this method after it runs through one set of the objects, the second set gives an “undefined” even though I have setup some triggers to check and it’s not actually going undefined.

var loadarray = JSON.parse(localStorage.getItem( 'savedme' ));
$.each(loadarray, function(k, v) {
     if(typeof k === 'undefined' || !k){
        console.error("undefined found at k!");
    };
     if(typeof v[0] === 'undefined' || !v[0]){
        console.error("undefined found at x!");
    };
     if(typeof v[1] === 'undefined' || !v[1]){
         console.error("undefined found at y!");
    };
});

so I’ve come to realize, I’m probably doing something wrong with arrays so I figured it would be faster to sort out the array and THEN use the same function. It HAS to be ordered like this because it’s basically going to be outputted to a matrix table, I tried ordering it like this:

  {
    "1":["1","Bob"],
    "2":["1","John"],
  } 

but…the index value 1 would just be overwritten by the last value

Answer

Keys cannot be sorted within an object.

However, they can be processed in order using Object.keys(object).sort().

Here, I’m outputting the object to an array – sorted by the keys’ values – then displaying that array:

var obj= {
 "Bob":["1","1"],
 "John":["2","1"],
 "Mom":["3","1"],
 "Dad":["1","2"],
 "Tom":["3","2"],
 "Skipper42":["2","3"],
 "Hated_41":["3","3"],
 "Greeneggs":["2","2"],
 "William":["1","3"]
}

var arr= Object.keys(obj)
          .sort(function(a, b) {
            if(obj[a][0]===obj[b][0]) {
              return obj[a][1] - obj[b][1];
            }
            else {
              return obj[a][0] - obj[b][0];
            }
          })
          .map(function(key) {
            var o= {};
            o[key]= obj[key];
            return o;
          });

document.body.innerHTML= JSON.stringify(arr);
Advertisement