Sort Multidimensional Array of Objects with Variable Depth in Javascript

advertisements

So I've recently come across a problem I can't seem to wrap my head around.

Let's say I've defined an array of objects in javascript, and want the user to be able to choose what value to sort that array by. I have no problem sorting the array when I know the depth, as it would be something along the lines of

array = array.sort(function (a, b) {
    return b["foo"]["bar"] - a["foo"]["bar"];
});

but I don't exactly know how to go about doing this when the depth is unknown. I've attempted putting the keys in a string and using eval(), but that does not seem to work.

I've set up a quick example on JSFiddle to better demonstrate what I mean http://jsfiddle.net/DakotaSv/c35bj02w/2/

If anyone could think of a solution, I'd be grateful!

(Thanks to PatrickD, here is the working JSFiddle for anyone who may find it useful!)


Here is a working solution. It uses ES6-Syntax, but this should not be a problem:

'use strict'

var users = [
  {'Name' : 'John', 'Attributes' : {'Age' : 5, 'Height' : 1.5, 'Clothes' : {'Shirts' : 5, 'Pants' : 8}}},
  {'Name' : 'Andrew', 'Attributes' : {'Age' : 9, 'Height' : 1.8, 'Clothes' : {'Shirts' : 2, 'Pants' : 5}}},
  {'Name' : 'Lucifer', 'Attributes' : {'Age' : 11, 'Height' : 1.3, 'Clothes' : {'Shirts' : 9, 'Pants' : 4}}}
];

function sort(valuePath, array){
  let path = valuePath.split('.')  

  return array.sort((a, b) => {
     return getValue(b,path) -  getValue(a,path)
  });

  function getValue(obj, path){
    path.forEach(path => obj = obj[path])
    return obj;
  }
}

console.log(sort('Attributes.Height', users))
console.log(sort('Attributes.Clothes.Shirts', users))

The output is correct.