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.

0

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

8 Comments

"returns a new array" .. again, no it doesn't
It does! if not then what is the array inside dataWords[] array?
Not the sort(), but the split()
That is not the correct way to compare arrays in Javascript
I was comparing the objects. If the original statement was accurate they would not have been same object reference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.