delz
delz

Reputation: 89

How does the function in this array filter work?

I'm doing a beginner exercise, find the mean/median/mode/range of var numbers = [23,9,14,2,28,19,3,15,9,25,2,4,9]. Mean was simple, but I have to get the numbers unique for the median. I came across something that works perfectly for that:

var numbersUnique = numbers.filter(
    function(i, j, k) {
        return j === k.indexOf(i);
    }
)

It even sorts them. I don't know how it works though. I skimmed this doc but there's nothing similar really.

I wasn't even aware that you could return something with a comparative operator. I thought it might be shorthand for if (j === k.indexOf(i)) { return j; } but that logs [3, 4, 9, 14, 15, 19, 23, 25, 28] not [2, 3, 4, 9, 14, 15, 19, 23, 25, 28] like the original one.

What is the function doing exactly?

Complete code

var numbers = [23, 9, 14, 2, 28, 19, 3, 15, 9, 25, 2, 4, 9];

// Mean

var numbersTotal = 0;

for (i = 0; i < numbers.length; i++) {
    numbersTotal += numbers[i];
}

var numbersMean = (numbersTotal / numbers.length);

console.log("The mean is " + numbersMean);

// Median

var numbersSorted = numbers.sort(function (a, b) {
    return a - b;
})

var numbersUnique = numbers.filter(function (i, j, k) {
    return j === k.indexOf(i);
})

console.log(numbersUnique);

Upvotes: 2

Views: 148

Answers (2)

Tushar
Tushar

Reputation: 87203

The filter function only keeps the elements for which the function returns true or truthy value.

In your case,

return j === k.indexOf(i);

Here,

  • i is the current element in the loop.
  • j is the current index in the loop
  • k is the input array

And k.indexOf(i) will return the first index of the element in the array. If the index of the current element in the loop, i.e. j is same as the first index in the array, it'll return true and false otherwise.

So, basically it return true for the first value in the array and if the array contain a value more than once(duplicate values) it returns false and the element is not included in the filtered array.


Giving meaningful names to the variables will make you easy to understand the code by just looking at it

var numbersUnique = numbers.filter(
    function (element, index, array) {
    //        ^^^^^^^                    The current element in the array
    //                 ^^^^^             The index of the current element in array
    //                        ^^^^^      Original Array

    return index === array.indexOf(element);
});

Note: When I used current in the above explanation it means the respective entity when looping.

Upvotes: 2

MysterX
MysterX

Reputation: 2368

Filter function must return 'true' or 'false'. First of all read attentively this Array.prototype.filter

and then you can explain to yourself how your filter function works

Upvotes: -1

Related Questions