Chonchol Mahmud Chonchol Mahmud - 6 months ago 11
Javascript Question

How to sort value in JavaScript?

How to sort in JavaScript for my case? I will input some value like given below:

Input:

banana
apple
orange
lichi
air
airness


I have found so:

$('.alphabetized').click(function(event) {
var textareaInput=$('.textareaInput').val();
var strToArr=textareaInput.split(',');
var arrUniqueVal=arrUnique(strToArr);
$('.textareaInput').val(arrUniqueVal.sort().join(','));
console.log(arrUniqueVal);
//alert("ok");
});


My code is work if i input something like this:

banana,apple,orange,lichi,air,airness


How can i split inputted array so that i can get result of my required inputted value (See input value in question) ?

Answer

Split based on new line instead of ,

var strToArr=textareaInput.split(/[\r\n]+/);

$('.alphabetized').click(function(event) {
  var textareaInput = $('.textareaInput').val();
  var strToArr = textareaInput.split(/[\r\n]+/);
  var arrUniqueVal = strToArr; //arrUnique(strToArr);
  $('.textareaInput').val(arrUniqueVal.sort().join('\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea rows=10 class="textareaInput"></textarea>
<button class="alphabetized">Sort</button>