0

Its simple like this. I need to sort an array with multiple values alphanumeric

this.tests = [

  {
    "title": "047 - Wunsc",
    "link": "47",
  },
  {
    "title": "014 - Expl",
    "link": "14",
  },
  {
    "title": "004 - Ausw",
    "link": "4",
  },
  {
    "title": "001 - Abhef",
    "link": "1",
  },
  {
    "title": "006 - Beurt",
    "link": "6",
  },
  {
    "title": "015 - Explo",
    "link": "15",
  },
  {
    "title": "029 - Physi",
    "link": "29",
  },
  {
    "title": "016 - Befra",
    "link": "16",
  }
]

This is what I've tried so far.

this.tests.sort(function (a, b) {
  return parseFloat(a.title) - parseFloat(b.title);
});

this.tests.sort((a, b) => a.title.localeCompare(b.title));

But still getting no alphanumeric/natural sort

3
  • 3
    What is the expected output? Commented Jul 3, 2020 at 11:46
  • 2
    this.test != this.tests Commented Jul 3, 2020 at 11:51
  • (Also, please don't post a question and leave. Please be available for clarifications) Commented Jul 3, 2020 at 12:09

1 Answer 1

1

For this pattern just sort by string.

var data = [{ title: "047 - Wunsc", link: "47" }, { title: "014 - Expl", link: "14" }, { title: "004 - Ausw", link: "4" }, { title: "001 - Abhef", link: "1" }, { title: "006 - Beurt", link: "6" }, { title: "015 - Explo", link: "15" }, { title: "029 - Physi", link: "29" }, { title: "016 - Befra", link: "16" }];

data.sort((a, b) => a.title.localeCompare(b.title));

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

If you like to sort only by description part, you could slice the string.

var data = [{ title: "047 - Wunsc", link: "47" }, { title: "014 - Expl", link: "14" }, { title: "004 - Ausw", link: "4" }, { title: "001 - Abhef", link: "1" }, { title: "006 - Beurt", link: "6" }, { title: "015 - Explo", link: "15" }, { title: "029 - Physi", link: "29" }, { title: "016 - Befra", link: "16" }];

data.sort((a, b) => a.title.slice(6).localeCompare(b.title.slice(6)));

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's already mentioned in the question (upd: the comment doesn't apply to the edited version of the answer)
@AndreyOzornin, for me, it looks like two sortings, one oafter the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.