0

I am having array of objects where i want to reduce the array and get the count of two properties. When my array length is more than one it works but when its one or less it doesn't

const data = [{id: 1, count:3 , alt_count: 2}, {id: 2, count:4 , alt_count: 5}];
const countObj = data.reduce((acc, curr) => {
      return {
        count_total: acc.count + curr.count,
        alt_count_total: acc.alt_count + curr.alt_count,
      };
    });
 console.log(countObj) // giving me both count_total and alt_count_total

But here its not giving me, instead it gives me the same object

const data = [{id: 1, count:3 , alt_count: 2}];
const countObj = data.reduce((acc, curr) => {
          return {
            count_total: acc.count + curr.count,
            alt_count_total: acc.alt_count + curr.alt_count,
          };
        });
console.log(countObj) // giving me entire first object

Any help is appreciated

1 Answer 1

3

You need to provide the initial value to reduce.

const data = [{
  id: 1,
  count: 3,
  alt_count: 2
}];

const countObj = data.reduce((acc, curr) => {
  return {
    count: acc.count + curr.count,
    alt_count: acc.alt_count + curr.alt_count,
  };
}, {
  count: 0,
  alt_count: 0
});

console.log(countObj);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.