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.
CodePudding user response:
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('')
CodePudding user response:
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);