简体   繁体   中英

How to replace null values using orderBy in lodash

How can I properly replace null values with different values like a string using orderby in lodash.

Currently this is what I am doing to replace null values with a string. I will use a separate foreach loop to replace the null values for .GroupDate with a string and then use the orderBy function.

test.forEach((e, i) => {
    if (e.GroupDate === null) {
      test[i].GroupDate = i.toString();
    }
});

test = orderBy(test, [c => c.GroupDate, c => c.Index, c => c.Date], ['desc', 'asc']);

If there a better way to replace the foreach loop and add this condition inside the orderBy ?

I tried this but it doesn't work:

let groupDateNumber = 0;

test = orderBy(test, [
    (c) => {
      if (c.GroupDate === null) {
        c.GroupDate = groupDateNumber.toString();
      }
      groupDateNumber++;
      return c.GroupDate, c => c.Index, c => c.Timestamp;
    }
], ['desc', 'asc']);

Your iteratee function is returning an array is that correct? I believe what you want is

let groupDateNumber = 0;

test = orderBy(test, [
    (c) => {
      if (c.GroupDate === null) {
        c.GroupDate = groupDateNumber.toString();
      }
      groupDateNumber++;
      return c.GroupDate;
    },
    c => c.Index,
    c => c.Timestamp
], ['desc', 'asc']);

Another way you could do this through use of lodash seq method _(value) and map and orderBy . This should use lazy evaluation so it should be efficient, although I'm not sure how well chaining works with orderBy and sortBy.

test = _(test)
  .map((e, i) => {
    if (e.GroupDate === null) {
      e.GroupDate = i.toString();
    }
    return e;
  })
  .orderBy([c => c.GroupDate, c => c.Index, c => c.Date], ['desc', 'asc'])
  .value()

You can use a function array as second parameter and check for null values:

const textIfNull = '';

test = orderBy(test, [c => c.GroupDate || textIfNull, c => c.Index, c => c.Date], ['desc', 'asc']);

I created a sandbox with an example for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM