Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load array of data into dataset format using React Native?

In my-scenario, I am trying to restructure the array before loading into line chart. Here,I am receiving props like: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191]

I want to restructure the data like below, before loading into line chart

   const dataTwo = [

{
          value: 26.727,
          svg: {
            fill: Colors.WHITE,
          },
        },
        {
          value: 26.952,
          svg: {
            fill: Colors.WHITE,
          },
        },
       {
          value: 12.132,
          svg: {
            fill: Colors.WHITE,
          },
        },,
        {
          value: 25.933,
          svg: {
            fill: Colors.WHITE,
          },
        },
        {
          value: 12.151,
          svg: {
            fill: Colors.WHITE,
          },
        },
        {
          value: 28.492,
          svg: {
            fill: Colors.WHITE,
          },
        },,
        {
          value: 12.134,
          svg: {
            fill: Colors.RED,
          },
        },
        {
          value: 12.134,
          svg: {
            fill: Colors.WHITE,
          },
        },

The array of last before index, I need to insert unique colour value.

like image 286
RN Dev Avatar asked Jun 27 '26 14:06

RN Dev


1 Answers

COnsider this example:

enum Colors {
    WHITE = 'white',
    RED = 'red'
}
const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191]

const DEFAULT_SVG = {
    fill: Colors.WHITE,
}


const makeElem = (value: number) => ({ value, svg: DEFAULT_SVG })

const applySvg = (value: { value: number, svg: { fill: Colors } }, index: number) => index === 6 ? {
    ...value,
    svg: {
        fill: Colors.RED,
    }
} : value
const predicate = (elem: number, index: number) => applySvg(makeElem(elem), index)

const builder = (props: number[]) =>
    props.map(predicate)

const result = builder(data)

Just pass your props to builder function

Playground

like image 120
captain-yossarian Avatar answered Jun 29 '26 04:06

captain-yossarian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!