-3

I need to count the number of record present inside array of objects as per key value using Javascript/Jquery. I am explaining my code below.

var arrResult = [{"name":"jim","amount":34,"date":"11/12/2015"},
  {"name":"carl","amount":120.11,"date":"11/12/2015"},
  {"name":"jim","amount":45,"date":"12/01/2015"},
  {"name":"stacy","amount":12.00,"date":"01/04/2016"},
  {"name":"stacy","amount":34.10,"date":"01/04/2016"},
  {"name":"stacy","amount":44.80,"date":"01/05/2016"}
];

The above is my array of object. Here I need to count the no of record as per same name value and my expected output is given below.

var output=[
         {"name":"jim","count":2},
         {"name":"carl","count":1},
         {"name":"stacy","count":3}
]
2

2 Answers 2

3

You can use reduce:

var arrResult = [{"name":"jim","amount":34,"date":"11/12/2015"},
  {"name":"carl","amount":120.11,"date":"11/12/2015"},
  {"name":"jim","amount":45,"date":"12/01/2015"},
  {"name":"stacy","amount":12.00,"date":"01/04/2016"},
  {"name":"stacy","amount":34.10,"date":"01/04/2016"},
  {"name":"stacy","amount":44.80,"date":"01/05/2016"}
];

var output = arrResult.reduce((acc, curr) => {
  if (!acc.some(({ name }) => name == curr.name)) {
    acc.push({ name: curr.name, count: 1 });
  } else {
    acc.find(({ name }) => name == curr.name).count++;
  }
  return acc;
}, []);

console.log(output);

ES5 syntax:

var arrResult = [{"name":"jim","amount":34,"date":"11/12/2015"},
  {"name":"carl","amount":120.11,"date":"11/12/2015"},
  {"name":"jim","amount":45,"date":"12/01/2015"},
  {"name":"stacy","amount":12.00,"date":"01/04/2016"},
  {"name":"stacy","amount":34.10,"date":"01/04/2016"},
  {"name":"stacy","amount":44.80,"date":"01/05/2016"}
];

var output = arrResult.reduce(function(acc, curr) {
  if (!acc.some(function(e) {
    return e.name == curr.name;
  })) {
    acc.push({ name: curr.name, count: 1 });
  } else {
    acc.find(function(e) {
      return e.name == curr.name;
    }).count++;
  }
  return acc;
}, []);

console.log(output);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Object.values() combied Array.prototype.reduce():

const arrResult = [{"name":"jim","amount":34,"date":"11/12/2015"},{"name":"carl","amount":120.11,"date":"11/12/2015"},{"name":"jim","amount":45,"date":"12/01/2015"},{"name":"stacy","amount":12.00,"date":"01/04/2016"},{"name":"stacy","amount":34.10,"date":"01/04/2016"},{"name":"stacy","amount":44.80,"date":"01/05/2016"}];
const output = Object.values(arrResult.reduce((a, c) => {
  a[c.name] = a[c.name] ? {name: c.name, count: ++a[c.name].count} : {name: c.name, count: 1};
  return a;
}, {}));

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.