user3200167
user3200167

Reputation:

Return specific elements in array with .filter?

I'm trying to learn some functional programming principles in javascript, but having some issues. I understand the iterative method (just a for loop), but I wanted to know if there was a functional programming style solution.

Say we have an array A where each element of A is another array, let's call these elements a:

A: [ Array[28], Array[28], ... ], where a_1..a_n is an array of size 28

Now say I only want the 5th element within a (so a[4]).

How would I do that using one of the higher order functions such as .map, .filter etc?

I've tried a method as such:

function myMethodThatReturns5thElem(n) {
 return n[4];
}

var arrayThatHas5thElements = A.filter(myMethodThatReturns5thElem);

but then arrayThatHas5thElementsis the same exact array as A..

Hopefully this makes sense.

Thank you.

Upvotes: 0

Views: 665

Answers (2)

tymeJV
tymeJV

Reputation: 104785

You want .map to return specific parts of the array:

var subset = A.map(function(inner) {
    return inner[4];
});

And if you want a single array - rather than a bunch of inner arrays with 1 element - just flatten the result:

var subsetFlattened = A.map(function(inner) {
    return inner[4];
}).reduce(function(p, c, i, a) {
    return p.concat(c);
}, []);

Upvotes: 0

Dalorzo
Dalorzo

Reputation: 20014

arr.filter(callback)

the callback function:

Returns true to keep the element, false otherwise.

So this means that your function arrayThatHas4thElement should return true in the when the item is the forth element

callback function receives 3 arguments:

  • value of the element
  • index of the element

You could use the 2nd parameter to evaluate what you are looking for.

Upvotes: 1

Related Questions