Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Javascript Sort by character appearance position

I have the following code:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
    const input = 'hello world';
    document.getElementById("demo").innerHTML = sortAlphabets(input);

    function sortAlphabets(input) {
        return input.split('').sort().join('');
    };
</script>

</body>
</html>

The result is: dehllloorw

But I want to change it to sort by character appearance position. The result should be: hellloowrd

How can I do that?
Really appreciated.

Thank you.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can use a compare function with .sort and inside that function you can use input.indexOf to get the index of the first appearance of the character in the input string.

input.split('').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')

EDIT

If you want spaces to be removed just use a filter after the split.

input.split('').filter(c=>c!==' ').sort((a,b) => input.indexOf(a)-input.indexOf(b)).join('')
about 4 years ago · Juan Pablo Isaza Report

0

You need a custom sort function, here will compare by index

const input = 'hello world';

let splited = input.split('').map(e => e.trim());

let sorted = splited.sort((a, b) => {
  return splited.indexOf(a) - splited.indexOf(b);
}).join('');

console.log(sorted);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!