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
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);
Comments
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
Rajaprabhu Aravindasamy
This will also throw the same error. arguments is not an array. Suggest him like
[...arguments].sort(compareNumbers); gurvinder372
@RajaprabhuAravindasamy you are right, just confirmed developer.mozilla.org/en/docs/Web/JavaScript/Reference/…