1

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!

1
  • 4
    You just need to add a return statement to your function so that it returns the sorted array :) Commented Oct 12, 2017 at 18:53

4 Answers 4

3

You can try this:

function sortByLength (array) {
   return array.sort((x,y) => x.length - y.length);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

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.