1

I'm trying to create a word and number sorting program for a class final, but I can't get array.sort to work with an HTML element.

<textarea name="data" placeholder="Input data here:" class="inputBox" id="dataInput"></textarea>

// sorting words
//moving HTML input into array
function addDataWords() {
//clear dataOutput
  let dataWords = [];
  document.getElementById('dataOutput').innerHTML = '';
//push into array
  dataWords.push(document.getElementById('dataInput').value.split(','));
  console.log(dataWords);
//sort words
  dataWords.sort();
  console.log(dataWords);
  document.getElementById('dataOutput').innerHTML = dataWords;
}

Debugger shows that HTML elements are being moved into the array, but .sort doesn't seem to sort them.

jkrasewicz
  • 13
  • 2

2 Answers2

2

The problem is split() returns an array. You are then pushing that array into the empty dataWords array as a sub array. So it would look like:

[['word1','word2'...]]

But you want ['word1','word2'...]

Just do :

let dataWords = document.getElementById('dataInput').value.split(',');

function addDataWords() { 
 
  // split comma delimited values into an array
  let dataWords =document.getElementById('dataInput').value.split(',');
  
  //sort words
  dataWords.sort();
  console.log(dataWords);
  document.getElementById('dataOutput').innerHTML = dataWords.join(', ');
}

addDataWords()
<textarea name="data" id="dataInput">foo,bar,two,one</textarea>

<div id="dataOutput"></div>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

JavaScript function .split() returns a new array.
So the output of your function is something like:

[['B', 'C', 'B']] // Example

So in this situation the easy solution is that you should sort the nested array

dataWords[0].sort();

Or a better way will be:

function addDataWords() {
  const dataWords = [];
  document.getElementById('dataOutput').innerHTML = '';

  const dataInput = document.getElementById('dataInput').value.split(','));
  for (let data of dataInput) {
     dataWords.push(data);
  }

  console.log(dataWords);
  document.getElementById('dataOutput').innerHTML = dataWords;
}
Masood
  • 1,545
  • 1
  • 19
  • 30