I'm writing a script for sheets using Google Apps script, and I'm passing an array as an argument into a function, and I'd like to sort the array inside, and return a new array that's also been manipulated a bit after it's been sorted. I took some code from another thread here
The code:
function removeDupes(array) {
var outArray = [];
array.sort(); //sort incoming array according to Unicode
outArray.push(array[0]); //first one auto goes into new array
for(var n in array){ //for each subsequent value:
if(outArray[outArray.length-1]!=array[n]){ //if the latest value in the new array does not equal this one we're considering, add this new one. Since the sort() method ensures all duplicates will be adjacent. V important! or else would only test if latestly added value equals it.
outArray.push(array[n]); //add this value to the array. else, continue.
}
}
return outArray;
}
array.sort(); returns the error
"TypeError: Cannot call method "sort" of undefined. (line 91, file "Code")"
. How can I perform the sort() method on the array passed into this function as an argument?
undefinedas the argument, even if unintentionally.removeDupes(array)isn't actually passing an array.undefinedas parameter, or called the dunction without one, btw. iterating withfor ... inis not advisable.for/inloops are for looping objects with keys, not arrays. Use.forEach()or a standard counting loop to iterate an array.