0

I need to create 2 arrays form one array with object that consist of 2 elements.

I've got array form axios call:

chartdata: Array [4]
  [{"total":3,"month":9},
   {"total":5,"month":5},
   {"total":9,"month":2},
   {"total":4,"month":1}]

How can i get array of totals and array of months?

2 Answers 2

1

This is a little bit "fancier" than the other suggestions, but it is not the most efficient solution. If performance is an issue, then you will need to use the map solutions others have posted.

// Your array.
const chartdata = [
  {"total":3,"month":9},
  {"total":5,"month":5},
  {"total":9,"month":2},
  {"total":4,"month":1}
];

// Easy way to get each set of values.
const [totals, months] = chartdata.reduce((current, next) => {
  return [
    current[0].concat(next.total),
    current[1].concat(next.month)
  ];
}, [[], []]);

console.log('Totals:', totals);
console.log('Months:', months);

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

1 Comment

@DavidWeldon => I appreciate the feedback. I edited my post to reflect your feedback on performance.
1

use the build-in javascript function map twice

totals = chartdata.map(function(item){ return item.total})
months= chartdata.map(function(item){ return item.month})

1 Comment

Thanks alot mate.

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.