Home > Blockchain >  javascript sorting by value, if the values are equal, sorting between equal items by a different val
javascript sorting by value, if the values are equal, sorting between equal items by a different val

Time:06-11

I have an object data, I sort this data according to their points, but if the points are the same, I want the last updated item to be on top. but I could not create the algorithm here. Can you help me ?

My JSON Data

[
  {
    "name": "Item 1",
    "point": 3,
    "updatedAt": "10/06/2022 9:39"
  },
  {
    "name": "Item 2",
    "point": 4,
    "updatedAt": "10/06/2022 9:45"
  },
  {
    "name": "Item 3",
    "point": 2,
    "updatedAt": "10/06/2022 9:39"
  },
  {
    "name": "Item 4",
    "point": 1,
    "updatedAt": "10/06/2022 9:39"
  },
  {
    "name": "Item 5",
    "point": 5,
    "updatedAt": "10/06/2022 9:39"
  },
  {
    "name": "Item 6",
    "point": 2,
    "updatedAt": "11/06/2022 3:05"
  }
]

For example, the points of Item 3 and Item 6 are the equal here, but Item 3 displays at the top. Because I added Item 6 later. So how do I get Item 6 to be above Item 3 if their points are equal?

I was planning to do this so that the last updated is at the top.

I tried several methods but it didn't work, for now this is my starting code.

if (sortBy === "lowtohigh") {
      computedData = data.sort((a, b) => {
        return a.point - b.point
      });
}
if (sortBy === "hightolow") {
      computedData = data.sort((a, b) => {
        return b.point - a.point
      });
}

Thank you for your answers in advance.

CodePudding user response:

Using Array#sort and Date (as fallback):

const arr = [
  { "name": "Item 1", "point": 3, "updatedAt": "10/06/2022 9:39" },
  { "name": "Item 2", "point": 4, "updatedAt": "10/06/2022 9:45" },
  { "name": "Item 3", "point": 2, "updatedAt": "10/06/2022 9:39" },
  { "name": "Item 4", "point": 1, "updatedAt": "10/06/2022 9:39" },
  { "name": "Item 5", "point": 5, "updatedAt": "10/06/2022 9:39" },
  { "name": "Item 6", "point": 2, "updatedAt": "11/06/2022 3:05" }
];

const res = arr.sort((a, b) => 
  a.point - b.point || new Date(b.updatedAt) - new Date(a.updatedAt)
);

console.log(res);

CodePudding user response:

If later numbered items have that naming convention and are always the most recently updated, check the order of items if points are equal:

computedData = data.sort((a, b) => {
    if (a.point - b.point) return a.point - b.point; // Change this line depending on asc or desc sort.
    else {
        return Number(a.name.split(" ")[1]) - Number(b.name.split(" ")[1]);
    }
});
  • Related