2

I have a javascript array. Something like this one:

let myObjects = [{
        'name': 'name 1',
        'date': '2017-04-15T22:00:00Z',
        'date2': '2017-04-12T22:00:00Z' },

      { 'name': 'name 2',
        'date': '2017-04-05T22:00:00Z' },

      { 'name': 'name 3',
        'date': '2017-04-05T22:00:00Z' },

      { 'name': 'name 4',
        'date': '2017-04-12T22:00:00Z',
        'date2': '2017-04-10T22:00:00Z' }];

I want to order myObjects by date2, but in case that the object does not have this attribute, it should be considered its date value.

I could just do it this way:

myObjects.map(function(obj){ if(!obj.date2){ obj['date2'] = obj['date']; }});
let orderedObjects = _.orderBy(myObjects, 'date2', true);

But I consider that it is a tricky solution. Could this be done just using the orderBy function without altering the original array?

cor
  • 3,323
  • 25
  • 46

2 Answers2

2

Use _.orderBy() with an iteratees function. For each element destructure date2, and date, and return date if date2 doesn't exist:

const myObjects = [{"name":"name 1","date":"2017-04-15T22:00:00Z","date2":"2017-04-12T22:00:00Z"},{"name":"name 2","date":"2017-04-05T22:00:00Z"},{"name":"name 3","date":"2017-04-05T22:00:00Z"},{"name":"name 4","date":"2017-04-12T22:00:00Z","date2":"2017-06-10T22:00:00Z"}];
        
const orderedObjects = _.orderBy(myObjects, ({ date2, date }) => date2 || date, true);

console.log(orderedObjects);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You can use _orderBy with a callback function that checks upon the date2 value if it exists otherwise upon date value.

This is how should be your call:

_.orderBy(myObjects, function(o) {
  return o.date2 ? o.date2 : o.date;
}, true);

Demo:

let myObjects = [{
    'name': 'name 1',
    'date': '2017-04-15T22:00:00Z',
    'date2': '2017-04-12T22:00:00Z'
  },

  {
    'name': 'name 2',
    'date': '2017-04-05T22:00:00Z'
  },

  {
    'name': 'name 3',
    'date': '2017-04-05T22:00:00Z'
  },

  {
    'name': 'name 4',
    'date': '2017-04-12T22:00:00Z',
    'date2': '2017-04-10T22:00:00Z'
  }
];

let ordered = _.orderBy(myObjects, function(o) {
  return o.date2 ? o.date2 : o.date;
}, true);

console.log(ordered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

You can check lodash orderBy on nested property where it shows a similar use case.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78