I did a sort function that passing an array as a parameter return a new array with the index positions sorted by the name of the item.
P.E: if the input is ["dog", "cat", "tiger"]
the expected output will be [1, 0, 2]
Without Prototype method
let sortIndexes = (a) => {
var aClone = a.slice(0);
return a.sort().map(x => aClone.indexOf(x));
}
let animals = ["dog", "cat", "tiger"];
var result = sortIndexes(animals);
console.log(result) // [1, 0, 2]
Well, this code works, but I think is better do the same adding an Array Prototype method. And I try it...
With Prototype
Array.prototype.sortIndexes = () => {
var aClone = this.slice(0); //Console Error in this line
return this.sort().map(x => aClone.indexOf(x));
}
let animals = ["dog", "cat", "tiger"];
var result = animals.sortIndexes();
I expected the same result that without using prototype, but this error console occurs:
Cannot read property 'slice' of undefined
How can do this using Array Prototype?
Thanks!