jkrasewicz
jkrasewicz

Reputation: 13

Sorting an Array from an HTML element using array.sort

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.

Upvotes: 1

Views: 67

Answers (2)

charlietfl
charlietfl

Reputation: 171669

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>

Upvotes: 2

Masood
Masood

Reputation: 1594

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;
}

Upvotes: 0

Related Questions