2

Here's what I mean. Suppose I have an array of objects like

var objs = [ { foo: 5, bar: "something"}, 
             { foo: 4912, bar: "blah" }, 
             { foo: -12, bar: "hehe" } ];

and an array that defines an ordering on bar values, like

var arr = ["blah", "something", "hehe"]

Does JavaScript have a good way of getting a version of objs to

[ { foo: 4912, bar: "blah" }, 
  { foo: 5, bar: "something"}
  { foo: -12, bar: "hehe" } ];

???

The best way I know is like

objs.sort(function(x,y){
    var ix = arr.indexOf(x), 
        iy = arr.indexOf(y);
    if(ix<iy) return -1;
    else if(ix==iy) return 0;
    else return 1;
});

but I'm wondering if there's a way that is more compact.

Ms. Corlib
  • 4,993
  • 4
  • 12
  • 19

3 Answers3

5

You can slightly refactor sort function:

objs.sort(function(x,y){
    var ix = arr.indexOf(x), 
        iy = arr.indexOf(y);
    return ix-iy;
});

Also, for better performance you may want to get rid of indexOf functions, and load sort array into hash:

var arr = {
    "blah" :0,
    "something":1,
     "hehe":2};

And sorting function will look like this:

objs.sort(function(x,y){
    return arr[x.bar]-arr[y.bar];
});
amaksr
  • 7,555
  • 2
  • 16
  • 17
2

The kind of sort you're wanting to do would go something like:

function inArray(v, a){
  for(var i=0,l=a.length; i<l; i++){
    if(a[i] === v){
      return true;
    }
  }
  return false;
}
function weirdSort(objsArray, objProperty, useArray){
  var r = [], c = [];
  for(var i=0,l=obsArray.length; i<l; i++){
    var o = objsArray[i];
    if(inArray(o[objProperty], useArray)){
      r.push(o);
    }
    else{
      c.push(o);
    }
  }
  return r.concat(c);
}
var result = weirdSort(obs, 'bar', arr);
StackSlave
  • 10,613
  • 2
  • 18
  • 35
0

Neither your original function, nor the code at the top of the currently accepted answer, actually sorts correctly. You need to reference the bar property in your sort function.

Try this:

var sortFunc = (ar,p) => (a,b) => ar.indexOf(a[p]) - ar.indexOf(b[p])

objs.sort(sortFunc(arr,"bar"))

Using a higher-order function gives you the flexibility to use any reference array you want, not one just named arr, and to sort based on any property in your objects, not just one named bar.

Josh
  • 4,726
  • 2
  • 20
  • 32