Ralfs R
Ralfs R

Reputation: 77

Cant sort words in ascending order by using sort method?

I think the problem is that javascript doesn't recognise that input field must be taken as an array

Where is the problem?

<!DOCTYPE html>
<html>
	<head>
		

		<script>
		
		function myFunction(){
		var longWords = new Array (document.getElementById("text").value);
		longWords.sort(function (a, b) {
		return b.length - a.length;
		})
		document.writeln(longWords);
		}	
		</script>

	</head>

	<body>
	<h1>Enter sentence in field</h1>
		<input id = "text" type = "text"/>
		<button onclick = "myFunction()">Sort text</button>
		
	</body>

</html>

Upvotes: 1

Views: 31

Answers (3)

sumit chauhan
sumit chauhan

Reputation: 1300

If you looking to sort a string and convert to array , have a look on below code snippet

var arr =[];
function convertToArray(text) {
  arr.push(text.split(''));
  console.log(arr);
}



function sortAlphabets(text) {
    console.log(text.split('').sort().join(''));
};
<input type="text" id="name">
<button onclick="sortAlphabets(document.getElementById('name').value);convertToArray(document.getElementById('name').value);">click</button>

Upvotes: 0

Dhaval Pankhaniya
Dhaval Pankhaniya

Reputation: 1996

<!DOCTYPE html>
<html>
	<head>
		

		<script>
		
		function myFunction(){
		var longWords = document.getElementById("text").value.split(' ');
		longWords.sort();
		document.writeln(longWords);
		}	
		</script>

	</head>

	<body>
	<h1>Enter sentence in field</h1>
		<input id = "text" type = "text"/>
		<button onclick = "myFunction()">Sort text</button>
		
	</body>

</html>

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

You could use String#split for spliting the string by space, then you get an array with words.

function myFunction() {
    var longWords = document.getElementById("text").value.split(' ');
    longWords.sort(function (a, b) {
        return b.length - a.length;
    });
    document.body.appendChild(document.createElement('br'));
    document.body.appendChild(document.createTextNode(longWords));
}	
<h1>Enter sentence in field</h1>
<input id = "text" type = "text"/>
<button onclick = "myFunction()">Sort text</button>

Upvotes: 3

Related Questions