2

This is straightforward using lodash:

var objects = [{ 'x': 4 }, { 'x': 4 }];
_.sortedIndexBy( objects, {'x':3}, 'x' );

But how to find an index when sorted on and accounting for multiple fields? For example:

var objects = [{ 'x': 4, 'y': 1 }, { 'x': 4, 'y': 3}];
_.sortedIndexBy( objects, {'x':4, 'y':6}, ['x', 'y'] );

(this second example does not work, but suggests what I am trying to do)

jedierikb
  • 12,752
  • 22
  • 95
  • 166

1 Answers1

2

Change the iteratee to a custom function that calculates a value where the value of x always takes precedence over the value of y:

_.sortedIndexBy( objects, {'x':4, 'y':6},  o => o.x * 1000 + o.y );
Gruff Bunny
  • 27,738
  • 10
  • 72
  • 59
  • Thanks! This approach gets complicated if dealing with fractional values, or if dealing with many fields or large values such that you expand past the number of digits available for padding. Was hoping there was an out of the box solution I had overlooked in lodash as _.sortBy works with multiple fields. – jedierikb Sep 08 '17 at 13:42
  • 2
    `sortBy` can take more than one iteratee whilst `sortedByIndex` can only take one. Which I'm afraid means you have to come up with some kind of algorithm for calculating the sort ranking. – Gruff Bunny Sep 08 '17 at 13:58