Steinroe Steinroe - 3 months ago 24
Javascript Question

Sorting nested array of objects with dynamic key

I am trying to create a sorting function that sorts a nested array of objects while giving a key dynamically (with different depths).

sortByKey(array, key){
var splitKey = key.split(".");
if(splitKey.length = 2){
return array.sort(function(a, b) {
var x = a[splitKey[0]][splitKey[1]]; var y = b[splitKey[0]][splitKey[1]];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
} else {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
}


I want to get rid of the
if - else
and use a
for
loop instead. The goal is that the function works with 'name', 'name.first' and 'name.first.another' (as an example). Is there a way to do this dynamically?

In other words, I want to use the same function with different arrays. So with one array I want to sort it calling sortByKey(array1, 'name') and with another sortByKey(array2, 'location.address') and maybe with a third sortByKey(array3, 'location.address.postalcode') or something like that.

Answer

Extract property extracting function

function prop(key) {
  var keys = key.split('.');

  return keys.reduce.bind(keys, function(obj, name) {
    return obj[name]
  })
}

and use it to well extract values :)

sortByKey(array, key){
    var getKey = prop(key);

    return array.sort(function(a, b){
      var x = getKey(a); var y = getKey(b);
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    })
  }