Home > Software engineering >  Newest date in dictionary using Javascript
Newest date in dictionary using Javascript

Time:08-26

Having an array of dictionaries I'd like to obtain the most updated record. For instance, consider the following record:

var myArray = [{
  itemA: {
  name: "Joe Blow",
  date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
  }, 
  itemB: {
  name: "Sam Snead",
  date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
  }, 
  itemC: {
  name: "John Smith",
  date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
  }}];

which then I would need to get the most updated record first:

myArray.sort((d1, d2) => new Date(d2.date).getTime() - new Date(d1.date).getTime());

However, I am not getting the correct result. Would you know how to get it working?

Thanks :)

CodePudding user response:

I have refactored your code a little bit.

first of all, your myArray contains only one object. you cannot sort an object like that. therefore I change the structure of your array.

here is a working example:

var myArray = [
  {
    id: 1,
    name: "Sam Snead",
    date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
  }, 
  {
    id: 2,
    name: "Joe Blow",
    date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
  }, 
  {
    id: 3,
    name: "John Smith",
    date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
  }
];


myArray.sort((d1, d2) => new Date(d2.date).getTime() - new Date(d1.date).getTime());

console.log(myArray)

CodePudding user response:

I'm assuming you want to sort the items in each entry by date. Right now you have just one entry in your array, but assuming you had many entries and wanted each sorted by date, here is a solution using the schema you provided for the data.

You can sort an object by sorting its keys with Object.keys(), though an array of entries might make more sense.

const myArray = [
  {
    itemA: {
      name: "Joe Blow",
      date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
    },
    itemC: {
      name: "John Smith",
      date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
    },
    itemB: {
      name: "Sam Snead",
      date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
    }
  }
];

const sortedEntries = myArray.map((entry) =>
  Object.keys(entry).sort(function (prev, next) {
    return new Date(entry[prev].date) < new Date(entry[next].date) ? -1 : 1;
  })
);

console.log(sortedEntries);

CodePudding user response:

If you want to find the record with the latest date, you can iterate through the collection and store a record if it satisfies the comparator.

const
  identityFn = (x) => x,
  findBy = (collection, accessor, comparator) => {
    let result, prev, record, i;
    if (collection && collection.length) {
      for (i = 0; i < collection.length; i  ) {
        record = collection[i];
        if (!prev || comparator(accessor(record), prev)) {
          result = record;
          prev = accessor(record);
        }
      };
    }
    return result;
  },
  findMax = (collection, accessor = identityFn) =>
    findBy(collection, accessor, (curr, prev) => curr > prev);

const
  myArray = [{
    itemA: { name: "Joe Blow"   , date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)" },
    itemB: { name: "Sam Snead"  , date: "Sun Mar 30 2016 00:00:00 GMT-0700 (PDT)" },
    itemC: { name: "John Smith" , date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)" },
  }],
  [key, record] = findMax(
    Object.entries(myArray[0]),          // Access the entries (key/val pairs)
    ([key, { date }]) => new Date(date)  // Map the parsed date
  );

console.log(record); // Data for key "itemC"
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you want to sort the records, you can modify the code above like so:

const sortBy = (collection, accessor, comparator) =>
  collection.sort((a, b) => comparator(accessor(a), accessor(b)));

const
  myArray = [{
    itemA: { name: "Joe Blow"   , date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)" },
    itemB: { name: "Sam Snead"  , date: "Sun Mar 30 2016 00:00:00 GMT-0700 (PDT)" },
    itemC: { name: "John Smith" , date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)" },
  }],
  sorted = sortBy(
    Object.entries(myArray[0]),          // Access the entries (key/val pairs)
    ([key, { date }]) => new Date(date), // Map the parsed date
    (curr, prev) => prev - curr          // Same as (DESC): (curr - prev) * -1
  );

console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important; }

CodePudding user response:

This snippet should help you:

const myArray = [
  {
    itemA: {
      name: "Joe Blow",
      date: "Mon Jan 31 2016 00:00:00 GMT-0700 (PDT)"
    },
    itemC: {
      name: "John Smith",
      date: "Sat Apr 29 2016 00:00:00 GMT-0700 (PDT)"
    },
    itemB: {
      name: "Sam Snead",
      date: "Sun March 30 2016 00:00:00 GMT-0700 (PDT)"
    }
  }
];

const sortedArray = myArray.map(entry => {
  let tmpObj = {};
  let tmpSorted =  Object.keys(entry).sort((prev, next) => {
    return Date.parse(entry[next]?.date) - Date.parse(entry[prev]?.date);
  });

  tmpSorted.forEach(e => {
    tmpObj[e] = entry[e];
  })

  return tmpObj;
});


console.log(sortedArray);
  • Related