1
function getIndexToIns(arr, num) {

  var args = Array.prototype.join.call(arguments);

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

  return args;

}

getIndexToIns([40, 60], 50);

2 Answers 2

2

The error was thrown simply because Array.prototype.join returns a string. In order to convert array-like objects to arrays, you need to use Array.prototype.slice.call instead.

Replace

 var args = Array.prototype.join.call(arguments);

with this

 var args = Array.prototype.slice.call(arguments);

or with Function.prototype.apply

var args = Array.apply(null, arguments);

or with Array.from

var args = Array.from(arguments);

The cleanest solution is ES6 rest parameters

function getIndexToIns(...args) {

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

  return args;

}

getIndexToIns([40, 60], 50);
Sign up to request clarification or add additional context in comments.

Comments

0

Because Array.prototype.join.call(arguments); will return a string rather than an array and String doesn't have a sort method.

Replace

var args = Array.prototype.join.call(arguments);

with

var args = Array.apply(null, arguments);

2 Comments

This will also throw the same error. arguments is not an array. Suggest him like [...arguments].sort(compareNumbers);
@RajaprabhuAravindasamy you are right, just confirmed developer.mozilla.org/en/docs/Web/JavaScript/Reference/…

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.