user5311029
user5311029

Reputation: 13

Return specific value with filter

Assuming you have an array of objects:

var arr = [{ a: 1 }, { a: 2 }, { a: 3 }];

And you want only the values of the a property of each object:

[1, 2, 3]

What functional approach can you use? I tried using filter:

arr.filter(x => x.a);

But of course, filter returns the whole object. Is there any other method I can use to achieve the result above? I mean, I could use forEach, I guess, or a for loop, but is there a better way? map would work IF I wanted all of the property values, but I would actually like to filter some of them out.

Upvotes: 1

Views: 680

Answers (2)

Millena
Millena

Reputation: 1

Javascript is the great thing to get the same result in different ways.

But the better way is to use a regular for loop (check Why most JavaScript native functions are slower than their native implementations?)

So you can do something like this:

var arr = [{ a: 1 }, { a: 2 }, { a: 3 }];
var newArray = [];
for(var i in arr) { // or you can use: for(var i=0;i<arr.length;i++)
	var newArrValue = arr[i].a;
	if(newArrValue<3) // or some other if conditions to filter the values
	newArray.push(newArrValue);
}
console.log(newArray);
// and you will get [1, 2] as a result with newArrValue<3 if condition

Upvotes: 0

user229044
user229044

Reputation: 239462

You want map to transform the type of each element. There is no magic filter that does a map as well; if you want to both filter and map, then you need to filter then map. These things are built to chain on purpose:

var arr = [{ a: 1 }, { a: 2 }, { a: 3 }];

arr.filter(x => x.a > 1).map(x => x.a) // => [2, 3]

Upvotes: 2

Related Questions