Search code examples
javascriptmethods

Is it possible to connect methods, like sort. shift, pop, push and unshift


I'm wondering if those that sort, shift, pop, push, unshift cannot be used whilst connecting to other method.

My current code is the following.

function trimmedAverages(arr) {   
    let sum = 0;
    arr.sort((a, b) => a - b);
    arr.shift();
    arr.pop();
    arr.map( x => sum += x);
    return Math.round(sum / arr.length);
}

And I thought it would be simple if I can connect them like the following one, but it returned an error message..

function trimmedAverages(arr) { 
    let sum = 0;
    arr.sort((a, b) => a - b).shift().pop();
    arr.map( x => sum += x);
    return Math.round(sum / arr.length);
}   
// Error : VM6710:3 Uncaught TypeError: arr.sort(...).shift(...).pop is not a function
// at trimmedAverages (<anonymous>:3:36)
// at <anonymous>:1:1

Is there anybody can explain for me please? Thank you so mush in advance.


Solution

  • You can't chain shift() and pop(), because shift() returns the element that was removed, not the updated array.

    For your needs you can use .slice() to get the sub-array without the first and last elements. And you can chain it from sort(), since it returns the array (in addition to modifying it in place).

    Since slice() doesn't modify the array, you need to subtract 2 from the length when calculating the average.

    function trimmedAverages(arr) {
        if (arr.length <= 2) { // return default value if array is too short
          return NaN;
        }
        let sum = 0;
        arr.sort((a, b) => a - b).slice(1, -1).forEach( x => sum += x);
        return Math.round(sum / (arr.length - 2));
    }
    
    console.log(trimmedAverages([1, 3, 10, 5, -6, 19, 20, -8]));