I have this function inside a Component:
import React, { Component } from 'react';
import CanvasJSReact from '../../assets/canvasjs.react';
import _ from 'lodash';
class MyChart extends Component {
constructor() {
super();
this.generateDataPoints = this.generateDataPoints.bind(this);
}
generateDataPoints(noOfDps) {
var xVal = 1, yVal = 100;
var dps = [];
for(var i = 0; i < noOfDps; i++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({x: xVal,y: yVal});
xVal++;
}
return dps;
}
render() {
var dataPoints = this.generateDataPoints(100);
console.log("dataPoints", dataPoints);
let yFirst = _.first(dataPoints);
let yLast = _.last(dataPoints);
let yMax = _.pick(dataPoints, 'y');
//console.log("Fisrt", yFirst, "Last:", yLast);
const {x: first, y: second } = dataPoints;
//let yMax = array.pick(dataPoints, 'y');
console.log("y", second);
}
return (...);
}
}
export default MyChart;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
My dataSet is a plot on time (x), I want to calculate the minimum and maximum of y and generate a third property on those points, like this:
{ x: 40, y: 65 },
{ x: 50, y: 85, indexLabel: "highest"},
{ x: 60, y: 68 },
I´ve been trying to separate the array from dps in two to find min and max but it never works. I´m trying it with lodash library.
You can use an auxiliary function to determine which dataPoint has the highest value (if I understood correctly, is the one that y
is bigger), then you set that property indexLabel = "highest"
into that object.
The same logic is used for the lowest, as you can see in the example code below
let dataPoints = [{x: 40, y: 65}, {x: 50, y: 85}, {x: 60, y: 68}]
function setHighestLowest(dtPoints) {
let highestIndex = -1;
let minimumIndex = -1;
let highestValue = 0;
let lowestValue = 0;
for (let i = 0; i < dtPoints.length; i++) {
let obj = dtPoints[i]
if (obj.y > highestValue) {
highestIndex = i;
highestValue = obj.y;
}
if (obj.y < lowestValue || i == 0) {
minimumIndex = i;
lowestValue = obj.y;
}
}
if (highestIndex > -1) {
dtPoints[highestIndex].indexLabel = "highest"
}
if (minimumIndex > -1) {
dtPoints[minimumIndex].indexLabel = "lowest"
}
}
setHighestLowest(dataPoints)
console.log(dataPoints)