0

I am trying to add a Library function for sorting Items in an array. Though I got link and way, but when trying to make a library function, this doesn't work. can someone help me out as it is responding undefined as result.

var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];

Array.prototype.sortItems = function(){
  this.sort((a,b) => a - b);
}

console.log(arr1.sortItems());

Reference:

enter image description here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

2
  • The solution is in the link you've added: "Return value: The sorted array. Note that the array is sorted in place, and no copy is made." Commented Jun 6, 2020 at 9:47
  • 2
    How do you want log a result without return from your function? Commented Jun 6, 2020 at 9:55

2 Answers 2

2

you need to return the result of this.sort()

var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];

Array.prototype.sortItems = function(){
  return this.sort((a,b) => a - b);
}

console.log(arr1.sortItems());
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

1

Try returning the result

var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];

Array.prototype.sortItems = function(){
  return this.sort((a,b) => a - b);
}

console.log(arr1.sortItems());

FYI, compareFunction is optional

var arr1 = [5, 4, 2, 6, 9, 2, 8, 1, 6];

console.log(arr1.sort());

1 Comment

yes 'compare function' is optional, but without it data like [5,4,2,1,100,57...] won't work! So, for proper working, its required!

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.