MuhammadJ MuhammadJ - 1 month ago 6
Javascript Question

Return values instead of objects in filter() method

I have this simple code:



function getStockOver(stocks) {
'use strict';
return stocks.filter(function (stock) {
return (stock.price > 150);
});
}

var stocks = [
{ symbol: 'XFX', price: 240.22, volume: 23432},
{ symbol: 'TNZ', price: 110.22, volume: 232},
{ symbol: 'JXJ', price: 340.22, volume: 5632}
];
var symbols = getStockOver(stocks);

console.log(symbols);





Check if the
stock.price > 150
through
.filter()
then return it, otherwise skip it.
But I want to return only the
price
in the new array that created through
.filter()
, not the whole object, How?

Note: I know this can be done through
.forEach()
but
.filter()
is way easier.

Answer

You could just add Array#map for the price only.

function getStockOver(stocks) {
    'use strict';
    return stocks.filter(function (stock) {
        return (stock.price > 150);
    }).map(function (stock) {
        return stock.price;
    });
}

var stocks = [
    { symbol: 'XFX', price: 240.22, volume: 23432},
    { symbol: 'TNZ', price: 110.22, volume: 232},
    { symbol: 'JXJ', price: 340.22, volume: 5632}
];
var symbols = getStockOver(stocks);

console.log(symbols);

Comments