What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows:

const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191]

The objective is to reformat the data as shown below before introducing it to the 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 requirement is to assign a unique color value to the second-to-last element in the array.

Answer №1

Consider this scenario:

enum Styles {
    BOLD = 'bold',
    ITALIC = 'italic'
}
const values = [15.827, 18.593, 10.347, 12.459, 14.937, 17.682]

const DEFAULT_CSS = {
    font: Styles.BOLD,
}


const makeStyle = (num: number) => ({ num, css: DEFAULT_CSS })

const applyCss = (numObj: { num: number, css: { font: Styles } }, idx: number) => idx === 3 ? {
    ...numObj,
    css: {
        font: Styles.ITALIC,
    }
} : numObj
const condition = (value: number, index: number) => applyCss(makeStyle(value), index)

const generator = (elements: number[]) =>
    elements.map(condition)

const resultOutcome = generator(values)

Simply insert your elements into the generator function

Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Potentially null object in react typescript

In my React application with TypeScript, I have completed the implementation of a chart but encountered an error in the following line: backgroundColor: gradientFill ? gradientFill : chartRef.current.data.datasets[0].backgroundColor, T ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Bootstrap Tags Input is unable to function properly with data stored locally

I am currently working on developing a Project Manager tool that allows for the addition of multiple individuals to a single project. To accomplish this, I decided to incorporate the use of Bootstrap Tags Input by following the examples provided for Typeah ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page Within my code, there is a div called #myDiv that defaults to an opacity of 0. Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below: #myDiv { opacity: 0; } #myDiv:hover { opacity: 1 ...

Unlimited digest loop in Angular.js caused by nested ng-repeat and filter

In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices. angular.module('abc').filter('searchFor', function(){ return ...

Is there a way to display the button just once in a map function while still retaining access to the iteration value?

Utilizing formik within material-ui for a form has been quite productive. I've implemented a map function to print text fields and managed to display the Submit button only once by targeting the index. However, there's an issue when attempting to ...

Exploring the possibilities of utilizing package.json exports within a TypeScript project

I have a local Typescript package that I am importing into a project using npm I ./path/to/midule. The JSON structure of the package.json for this package is as follows: { "name": "my_package", "version": "1.0.0&q ...

Passing props through Link in React can be a tricky process, especially when encountering issues with undefined props like this

My latest project involves creating a recipe research tool in react. The homepage features buttons that allow me to search for recipes and view them based on the data I gather. However, when I try to access the state values using 'console.log(this.pro ...

Object is not compliant with HTMLInputElement interface and cannot execute 'stepUp'

Currently, I am facing an issue with passing the selected value from a dropdown list of countries to a PHP file using AJAX. The goal is to take this value and then transfer it to another input field identified by the ID #tele. Here is the gist of my code: ...

Unlocking the Potential of Checkbox Values in AngularJS

I am attempting to extract data from a $rootScope object that has been linked to the checkboxes. HTML: <tr ng-repeat="system_history in SystemHistoryResponse.system_history"> <td><input type="checkbox" ng-model="versionValues[system_histor ...

Attempting to retrieve all elements... held within a parent object in JavaScript

Currently diving into JS, Jest testing, and React - quite the ride! { '1': { accountName: 'Dance Party', balance: 200, key: 1 }, '2': { accountName: 'Whiskey Party', balance: 69, key: 2 }, '3& ...

Prevent IonContent from scrolling to the bottom or top when using Ionic framework

In my Ionic app, I have a long text page with 2 buttons that trigger the actions scrollToBottom and scrollToTop. Due to the length of the page, I have set the scroll duration to be 30 seconds. I am facing two issues here: How can I stop the scrolling ...

Errors and warnings caught off guard while running json-server with the --watch flag

I'm having some trouble using json-server in the following way: $ json-server --watch db.json Every time I try to run that command, I encounter errors or warnings depending on the version of json-server that is installed: 1.0.0-alpha.1-1.0.0-alpha.1 ...

The onScroll event is failing to trigger when scrolling to a particular div on Next.js

Is there a way to fetch data when a specific div comes into view on a SSR page in Next.js? I attempted using the onScroll event on the div, but it doesn't seem to be triggering. Any suggestions? function handleScroll() { console.log("scrolled ...

Locate a class using an interface

Consider the code snippet below: interface FirstInterface {} interface SecondInterface {} interface ThirdInterface {} class TheClass { constructor(howdy: FirstInterface) {} } class Foo implements FirstInterface {} class Bar implements SecondInterface ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

JavaScript's setAttribute function is not functioning as expected

I have been using the setAttribue method as shown below. It works perfectly for the first instance, but after that, when I try to change the value, it displays an alert without updating with document.getElementById("to").setAttribute("value", selValue); d ...