Andrey Orlov
Andrey Orlov

Reputation: 23

Why do I keep getting a TypeError: args.sort is not a function?

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

Upvotes: 1

Views: 3600

Answers (2)

Lewis
Lewis

Reputation: 14906

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

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68413

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

Upvotes: 0

Related Questions