Le Sparte
Le Sparte

Reputation: 163

Sort an array containing length values

I'm trying to sort an array with automatically generated values, but JS gives me strange results (console.log gives [14, 2, 3, 7, 9]). What should I add to get [2, 3, 7, 9, 14]?

let text ="Why so serious? Mathematicians shouldn't!";

// clean text
let cleaned_text_1 = text.replace(/[.,?!()]/g,"");
let cleaned_text_2 = cleaned_text_1.replace(/-/g," ");

// split text
let cleaned_text = cleaned_text_2.split(/\s/);

// create the length array
let array_lengths = [];
cleaned_text.forEach(function(d){
  array_lengths.push(d.length)
});

// sort the array
sorted_array = array_lengths.sort();
console.log(sorted_array);

Upvotes: 1

Views: 37

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

Actually Array#sort without callback sorts by strings. You need to sort by numbers with the delta of the values.

array_lengths.sort(function (a, b) {
    return a - b;
});

You need no assignment of the sorted array, because the sort works in situ (in-place).

Upvotes: 3

Related Questions