简体   繁体   中英

Sort an array by string length within a function

I have a problem that wants me to take an array of words, and return them in an array from smallest to largest word. This has to be done in a function. I have a simple form of it that is returning the results I desire:

//arr = ["Beg", "Life", "I", "To"]
//arr.sort(function(a, b){
//  return a.length - b.length;
//});

But I need to put it into a function. Here is what I have thus far with that part:

function sortByLength (array) {
    array.sort(function(a, b){
       return a.length - b.length;
    });
}
sortByLength(["Telescopes", "Glasses", "Eyes", "Monocles"]); 

I am not looking for the answer. Just some advice as to what I am doing wrong. Thanks for your help!

You can try this:

function sortByLength (array) {
   return array.sort((x,y) => x.length - y.length);
}

Looks like this works? If you set some variable to the sortByLength output is it right?

In your sortByLength function, you're not returning anything, so it's undefined. Consider putting a return just before the array.sort()

Yeah well just return the array. But as sorting sorts the passed array, it might be good to use .slice for copying it. Boiled down to an arrow func:

const sortByLength = arr => arr.slice().sort((a,b)=>a.length-b.length);

Or if you wanna do that faster ( maybe ) with a length table:

const sortByLength = arr => 
  arr.reduce((table,s)=> ( 
    (table[s.length] || (table[s.length] = [])).push(s), table), 
    []
  ).reduce((result, tablerow) => 
    result.concat(tablerow),
    []
);

Yup that ugly thing works ;)

You're not actually returning your value, you just need a return statement inside your sortByLength function:

 function sortByLength(array) { return array.sort(function(a, b) { return a.length - b.length; }); } console.log(sortByLength(["Telescopes", "Glasses", "Eyes", "Monocles"])); 

Edit : if you don't want to modify the original array, just add a slice() into the function and it will return a new array:

function sortByLength(array) {
  return array.slice().sort(function(a, b) {
    return a.length - b.length;
  });
}

var arrayOne = ["Telescopes", "Glasses", "Eyes", "Monocles"];
var arrayTwo = sortByLength(arrayOne);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM