简体   繁体   中英

Can't sort array passed as argument into function (TypeError, cannot call method sort of undefined)

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?

The error is very clear, whatever code you are using to call removeDupes isn't passing an actual array otherwise the .sort() method would work on the incoming argument. [Side note: why do you need to sort the array if you are interested in removing duplicates anyway?]

Beyond that, the Array.filter() method can filter out duplicates without you having to do all the looping. And, even when you do loop an array, you should not use for/in loops, as they are for enumerating objects with string key names, not arrays. Array looping should be done with regular counting loops, .forEach() or one of the many customized Array.prototype looping methods.

 var testArray = ["apple", "bannana", "orange", "apple", "orange"]; function removeDupes(arr){ // The .filter method iterates all of the array items and invokes a // callback function on each iteration. The callback function itself // is automatically passed a reference to the current array item being // enumerated, the index of that item in the array and a reference to // the array being iterated. A new array is returned from filter that // contains whatever the callback function returns. return arr.filter( function( item, index, inputArray ) { // If the index of the item currently being enumerated is the same // as the index of the first occurence of the item in the array, return // the item. If not, don't. return inputArray.indexOf(item) == index; }); } var filteredArray = removeDupes(testArray); console.log(filteredArray); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM