skip to Main Content

I am trying to sort an array of objects and the sorting will be done based on property which will be dynamic

I have an array

const fruitDetails = [
  {item: "Berry", qty: "651042446", stockDate: "2021-09-20"},
  {item: "Apple", qty: "23222", stockDate: "2023-08-10"},
  {item: "Kiwi", qty: "132345", stockDate: "2022-10-23"}
];

Now the sorting could be of on item, qty or stockDate

A function to sort this array of objects with dynamic property

function sortedData(column) {
  return fruitDetails.sort((a, b) => {
     if (a[column].toLowerCase() > b[column].toLowerCase()) {
       return 1;
     }
     if (a[column].toLowerCase() < b[column].toLowerCase()) {
       return -1;
     }
     return 0;
  });
}


console.log(sortedData("item"));
console.log(sortedData("qty"));
console.log(sortedData("stockDate"));

If you check the console output the sorted value for item and stockDate is correct but the qty sorted value is incorrect.

This is the console output for qty:

[{
  item: "Kiwi",
  qty: "132345",
  stockDate: "2022-10-23"
}, {
  item: "Apple",
  qty: "23222",
  stockDate: "2023-08-10"
}, {
  item: "Berry",
  qty: "651042446",
  stockDate: "2021-09-20"
}]

The qty value 23222 is smaller than the 132345 so Apple should be 1st, Kiwi 2nd and Berry 3rd.

I am adding the jsfiddle link for reference.
Please let me know what I am doing wrong here, thank you 🙂

2

Answers


  1. const fruitDetails = [{
        item: "Berry",
        qty: "651042446",
        stockDate: "2021-09-20"
      },
      {
        item: "Apple",
        qty: "23222",
        stockDate: "2023-08-10"
      },
      {
        item: "Kiwi",
        qty: "132345",
        stockDate: "2022-10-23"
      }
    ];
    
    function filters(key) {
      return fruitDetails.sort((a, b) => {
        if (key === 'item') {
          return a[key].localeCompare(b[key])
        } else if (key === 'qty') {
          return a[key] - (b[key]);
        } else if (key === 'stockDate') {
          return new Date(a[key]) - new Date((b[key]));
        }
      })
    }
    console.log(filters("item"));
    console.log(filters("qty"));
    console.log(filters("stockDate"));
    Login or Signup to reply.
  2. You can use regular expressions to test for numbers, then you would subtract the numbers (converted from strings) as you normally would when sorting numbers. Otherwise use the String#localCompare method as follows; strings and "date strings" in the format provided should sort fine with .localeCompare():

    const fruitDetails = [
      {item: "Berry", qty: "651042446", stockDate: "2021-09-20"},
      {item: "Apple", qty: "23222", stockDate: "2023-08-10"},
      {item: "Kiwi", qty: "132345", stockDate: "2022-10-23"}
    ];
    
    function sortedData(column) { //ascending order
      return fruitDetails.sort((a, b) => {
         const numRe = /^[0-9]*$/;
         if (numRe.test(a[column]) && numRe.test(b[column])) {
             return +a[column] - +b[column];
         } else {
             return a[column].localeCompare(b[column]);
         }
      });
    }
    
    
    console.log(sortedData("item"));
    console.log(sortedData("qty"));
    console.log(sortedData("stockDate"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search