Reputation:
I have multiple array of objects with two different ids, how to calculate the length of objects based on the id.
arr.filter(el=> {
if(el.p_id == "mobile"){
mobile_lenght = el.length}
else{
electronics_length = el.length
}
arr = [{id:"1", p_id:"mobile", c_code:"aaa"},
{id:"2", p_id:"electronics", c_code:"aaa"},
{id:"1", p_id:"mobile", c_code:"bbb"},
{id:"2", p_id:"electronics", c_code:"bbb"}]
expected output
mobile_length = 2;
electronics_length = 2;
Upvotes: 0
Views: 527
Reputation: 50797
You can write a generic function that counts elements matching a key you generate. Then, by passing it a function that returns an object's p_id
, you can get the result you want.
const countBy = (fn) => (xs) =>
xs .reduce ((a, x, _, __, key = fn (x)) => ({... a, [key]: (a[key] || 0) + 1}), {})
const arr = [{id:"1", p_id:"mobile", c_code:"aaa"}, {id:"2", p_id:"electronics", c_code:"aaa"}, {id:"1", p_id:"mobile", c_code:"bbb"}, {id:"2", p_id:"electronics", c_code:"bbb"}]
console .log (
countBy (x => x .p_id) (arr) //=> {mobile: 2, electronics: 2}
)
If you would rather this output:
{mobile_length: 2, electronics_length: 2}
then you can just call it like this instead:
countBy (x => `${x .p_id}_length`) (arr)
countBy
is a general utility function that you might reuse across an application or in multiple different applications.
Upvotes: 0
Reputation: 3253
const arr = [{id:"1", p_id:"mobile", c_code:"aaa"},
{id:"2", p_id:"electronics", c_code:"aaa"},
{id:"1", p_id:"mobile", c_code:"bbb"},
{id:"2", p_id:"electronics", c_code:"bbb"}]
const calc = (id) => arr.filter((el) => el.p_id === id).length
const result = calc("mobile");
console.log(result);
Upvotes: 2