0

I have a JSON data which look like this:

 {
  "chart":[
     [
        1627776011000,
        28
     ],
     [
        1627776371000,
        38
     ],
     [
        1627776731000,
        48
     ],
     ...
    ]
}

I want to use this data in Chart.js where 1627776011000 ... are x axis values and 28 ... are y axis values.

I know I can do it with an array push

const myArr = JSON.parse(dataJSON);

const data = []; 
const labels = [];

myArr.chart.forEach((item) => {
    labels.push(item[0]);
    data.push(item[1]);
});

but could there be a better way, for example with a map?

2
  • You could use reduce, but the way you do it is just fine. Try not to look for the "perfect" solution, it is much more practical to settle with a working solution. Commented Dec 13, 2021 at 18:14
  • What do you mean by "better"? Opinion-based questions are off-topic on Stack Overflow. Commented Dec 14, 2021 at 15:52

3 Answers 3

1

You can do it as two calls to map():

const labels = myArr.chart.map(el => el[0]);
const data = myArr.chart.map(el => el[1]);
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. perfect! Would you know roughly how much faster is this than array push from question?
maybe slower since it has to do two loops. But maybe faster because it can allocate the result arrays at once instead of growing incrementally. You'll need to profile it.
1

This seems to me like an invented problem.

If your data points are just x and y values, there's nothing wrong with saying the first array element is x and the second is y.

There are some people who would argue and say you should make it an Object with properties like xValue and yValue.

However, any upsides or downsides in either case would be marginal. You could imagine someone saying the Object version is more readable. The Object version is harder to optimize by the javascript runtime (V8 at least): https://v8.dev/blog/elements-kinds

Unless you have measured it, and it matters, it doesn't matter.

Comments

1

You can use .reduce() in as follows:

const myArr = {
  "chart":[
     [
        1627776011000,
        28
     ],
     [
        1627776371000,
        38
     ],
     [
        1627776731000,
        48
     ]
    ]
};

const [labels, data] = myArr.chart.reduce((acc,cur) => [
    [...acc[0], cur[0]],
    [...acc[1],cur[1]]],
[[],[]]);
console.log( labels, data );

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.