0

I am having problems sorting array of objects of this format

const arr = [
  { name: "test_1", age: 15 },
  { name: "test_11", age: 20 },
  { name: "test_12", age: 34 },
  { name: "test_2", age: 35 },
  { name: "test", age: 39 },
  { name: "example", age: 35 },
];

With the code that I have tried, it sorts based on string, hence I am getting wrong output. Can someone help me out with this using lodash

import orderby from "lodash.orderby";
const arr = [
  { name: "test_1", age: 15 },
  { name: "test_11", age: 20 },
  { name: "test_12", age: 34 },
  { name: "test_2", age: 35 }
];

function sortArr(field, order) {
  const result = orderby(
    arr,
    [
      (item) =>
        typeof item[field] === "string"
          ? item[field].toLocaleLowerCase()
          : item[field]
    ],
    order
  );
  return result;
}
console.log(sortArr("name", "asc"));

Output that I am expecting, test_1 test_2 test_11 test_12

Help wil be appreciated

  • Does this answer your question? [How to sort data which mix text and number?](https://stackoverflow.com/questions/56324302/how-to-sort-data-which-mix-text-and-number) – Hassan Imam Aug 10 '21 at 11:54
  • What you want is often called "natural sort" (I don't know if Lodash uses that term). – Álvaro González Aug 10 '21 at 11:56

1 Answers1

0

If using lodash isn't a requirement here, you could use JavaScript's built in array#sort like this:

arr.sort(
    (a, b) =>
        parseInt(a.name.replace(/[^0-9]/g, "")) -
        parseInt(b.name.replace(/[^0-9]/g, ""))
);

Demo:

const arr = [
  { name: "test_1", age: 15 },
  { name: "test_11", age: 20 },
  { name: "test_12", age: 34 },
  { name: "test_2", age: 35 },
  {name: "test^34", age: 33},
  {name: "13&&test", age: 27},
];

let sorted = arr.sort((a, b) => parseInt(a.name.replace(/[^0-9]/g, "")) - parseInt(b.name.replace(/[^0-9]/g, "")))

console.log(sorted)

If lodash is a requirement you can use lodash's _.sortBy, like this:

_.sortBy(arr, [(a) => _.toNumber(_.replace(a.name, /[^0-9]/g, ""))])

Demo:

const arr = [
  { name: "test_1", age: 15 },
  { name: "test_11", age: 20 },
  { name: "test_12", age: 34 },
  { name: "test_2", age: 35 },
  { name: "8-test", age: 23 },
];

let sorted = _.sortBy(arr, [(a) => _.toNumber(_.replace(a.name, /[^0-9]/g, ""))])

console.log(sorted)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>
lejlun
  • 4,140
  • 2
  • 15
  • 31