adplus-dvertising

Sort() in JavaScript

Asked 6 months ago
Viewed 19 times

Hello friends

  • how to arrange a number string with several characters?
  • I converted to a number, but it only gives me one 2
     <input type="text" name="numbers" id="numbers" readonly value="2, 4, 14, 10, 90, 23, 16"/>
    
     <button type="button" id="run">Lancer le script</button>
    

Run the script

(() => {
// to get the value of an input: document.getElementById("element-id").value

document.getElementById("run").addEventListener("click", () => {
   
   
});

})();

asked 6 months ago

Correct Answer

You can't directly convert "2, 4, 14, 10, 90, 23, 16" to "a number" because that string isn't a number. It's several different numbers.

What you're looking for is an array of numbers. First, split the string into an array of strings. Second, remove non-numeric characters from each element in the resulting array. Finally, convert each element of the array into a number. The result of that is also an array.

For example:

var input = '2, 4, 14, 10, 90, 23, 16';
console.log('input', input);

var firstStep = input.split(',');
console.log('firstStep', firstStep);

var secondStep = firstStep.map(x => x.trim());
console.log('secondStep', secondStep);

var thirdStep = secondStep.map(x => parseInt(x));
console.log('thirdStep', thirdStep);

Of course, the steps can be combined into a shorter example. They are separated here to demonstrate for you.

answered 6 months ago