0

I am trying to sort an array of s3 buckets based on the creation date (lastest first). I am getting the same array repeated multiple times in the sorted array. I know I am missing something here but am unable to figure out what. My code is:

var bucketListArr = [];
for (var index in data.Buckets) {
    var bucket = data.Buckets[index];
    //if(bucketList[index] == null) bucketList[index] = [];
    bucketListArr.push({
         "bucketName": bucket.Name,
         "creationDate": bucket.CreationDate
    });
    // bucketList[index][0] = bucket.Name;
   // bucketList[index][1] = bucket.CreationDate;
 }

 var sortedBucketListArr = [];
 //console.log("Bucket List :: ", bucketList, " length :: " , bucketList.length );
 for(var i= 0;i < bucketListArr.length; i++){
    for(var j = i + 1; j< bucketListArr.length; j++){
       if(bucketListArr[i].creationDate >= bucketListArr[j].creationDate){
          sortedBucketListArr.push({
                   "bucketName": bucketListArr[i].bucketName,
                   "creationDate": bucketListArr[i].creationDate
          });
     }
   }
 }
 console.log("Sorted List :: ", sortedBucketListArr);

Thanks in advance for any help.

Pallavi Prasad
  • 577
  • 2
  • 9
  • 28

1 Answers1

0

I was able to solve this problem. The problem was that the date is stored as a string. So it needs to converted to a Date before the array can be sorted on the date property. I altered my code to:

var bucketListArr = [];
for (var index in data.Buckets) {
    var bucket = data.Buckets[index];
    //if(bucketList[index] == null) bucketList[index] = [];
    bucketListArr.push({
         "bucketName": bucket.Name,
         "creationDate": bucket.CreationDate
    });
}
bucketListArr.sort(function (a, b) {
        var dateA = a.creationDate, dateB = b.creationDate;
        return dateB - dateA;//a.strParamToSortOn < b.strParamToSortOn;
});
console.log("Sorted List :: ", bucketListArr);
Pallavi Prasad
  • 577
  • 2
  • 9
  • 28