Popular Posts

Saturday, May 20, 2017

Doing group by like in JavaScript using the reduce function, see:


var countriesSubscription = [
{ Exchange: 'ASX', CountryId: 1, ExchangeRate: 1, CountryName: "Australia", Code: "AU", CurrencyForeign: "AUD", CurrencyLocal: "AUD", IsSubscribed: true, PriceLocal: 15.75, PriceForeign: null, DataType: "ClickToRefresh" },
{ Exchange: 'ASX', CountryId: 2, ExchangeRate: 1.01, CountryName: "Canada", Code: "CAN", CurrencyForeign: "CAD", CurrencyLocal: "AUD", IsSubscribed: false, PriceLocal: null, PriceForeign: null, DataType: "" },
{ Exchange: 'ASX', CountryId: 3, ExchangeRate: 5.78, CountryName: "Hong Kong", Code: "HKG", CurrencyForeign: "HKD", CurrencyLocal: "AUD", IsSubscribed: false, PriceLocal: null, PriceForeign: null, DataType: "" },
{ Exchange: 'CHIX', CountryId: 4, ExchangeRate: 0.74, CountryName: "US", Code: "USA", CurrencyForeign: "USD", CurrencyLocal: "AUD", IsSubscribed: true, PriceLocal: null, PriceForeign: null, DataType: "" },
{ Exchange: 'ASX', CountryId: 5, ExchangeRate: 0.67, CountryName: "France", Code: "FRA", CurrencyForeign: "EUR", CurrencyLocal: "AUD", IsSubscribed: false, PriceLocal: null, PriceForeign: null, DataType: "" },
{ Exchange: 'CHIX', CountryId: 6, ExchangeRate: 1.37, CountryName: "Switzerland", Code: "CHE", CurrencyForeign: "CHF", CurrencyLocal: "AUD", IsSubscribed: true, PriceLocal: null, PriceForeign: null, DataType: "" },
{ Exchange: 'ASX', CountryId: 7, ExchangeRate: 0.73, CountryName: "Belgium", Code: "BEL", CurrencyForeign: "EUR", CurrencyLocal: "AUD", IsSubscribed: false, PriceLocal: null, PriceForeign: null, DataType: "" },
];


// **** Array to group by Exchange ****
var groupByCurrency = countriesSubscription.reduce(function(all, item, index){
all[item.Exchange].push(item);
return all;
}, {CHIX:[], ASX:[]});

groupByCurrency.ASX.forEach(function(item){
console.log(item);
})

groupByCurrency.CHIX.forEach(function(item){
console.log(item);
})


output:

CountryId: 5, ExchangeRate: 0.67, CountryName: 'France', Code: 'FRA', CurrencyForeign: 'EUR', CurrencyLocal: 'AUD', IsSubscribed: false, PriceLocal: null, PriceForeign: null, DataType: '' } { Exchange: 'ASX', CountryId: 7, ExchangeRate: 0.73, CountryName: 'Belgium', Code: 'BEL', CurrencyForeign: 'EUR', CurrencyLocal: 'AUD', IsSubscribed: false, PriceLocal: null, PriceForeign: null, DataType: '' }

{ Exchange: 'CHIX', CountryId: 4, ExchangeRate: 0.74, CountryName: 'US', Code: 'USA', CurrencyForeign: 'USD', CurrencyLocal: 'AUD', IsSubscribed: true, PriceLocal: null, PriceForeign: null, DataType: '' } { Exchange: 'CHIX', CountryId: 6, ExchangeRate: 1.37, CountryName: 'Switzerland', Code: 'CHE', CurrencyForeign: 'CHF', CurrencyLocal: 'AUD', IsSubscribed: true, PriceLocal: null, PriceForeign: null, DataType: '' }  

No comments:

Post a Comment