Getting the max for an Api json data in react - reactjs

I have fetched an Api data which is "PRICES" , and I'm trying to get the maximum for it but this function is not working , I would appreciate any help !
const pricedata = {
datasets: [
{
backgroundColor: '#0000',
barPercentage: 2,
barThickness: 5,
data: PRICES,
label: 'Update in prices',
maxBarThickness: 10
},
],
};
function findMax(PRICES) {
if (!PRICES) {
return;
}
return Math.max(...PRICES);
}
console.log(findMax())

I added the "price data" where you have PRICES in the data and added a 2nd chunk of data for illustration.
The code below loops over each "dataset" and, finds the max price and adds it as a new key called "maxPrice". Then it prints them out. This is just one way.
const pricedata = {
datasets: [
{
backgroundColor: "#0000",
barPercentage: 2,
barThickness: 5,
data: [1, 10, 30, 7, 42, 12],
label: "Update in prices",
maxBarThickness: 10
},
{
backgroundColor: "#0000",
barPercentage: 2,
barThickness: 5,
data: [11, 70, 18, 17, 24, 12],
label: "Update in prices",
maxBarThickness: 10
}
]
};
function findMax(PRICES) {
if (!PRICES) {
return 0;
}
return Math.max(...PRICES);
}
pricedata.datasets.forEach((dataset) => {
dataset.maxPrice = findMax(dataset.data);
});
pricedata.datasets.forEach((dataset) => {
console.log('max price is', dataset.maxPrice);
});
Update:
Use a reducer to get the max of all the products...
const maxOfAllProducts = pricedata.datasets.reduce((accumulator, current) => Math.max(current.maxPrice, accumulator),0);
console.log('max of all products', maxOfAllProducts)

You forgot to put the PRICES variable in the function call on the last line
let PRICES = [1,2,3,4,5,6,7,8,9,10];
function findMax(PRICES) {
if (!PRICES) {
return;
}
return Math.max(...PRICES);
}
console.log(findMax(PRICES)) // outputs 10
OR remove that variable in the function
let PRICES = [1,2,3,4,5,6,7,8,9,10];
function findMax() {
if (!PRICES) {
return;
}
return Math.max(...PRICES);
}
console.log(findMax()) //outputs 10

Related

How to make Highcharts ticks distributed evenly no matter what the tick values are

I created a bar chart with some chart options with Highcharts React
https://codesandbox.io/s/highchart-bar-uneven-ticks-c6mi5p
The ticks are not distributed evenly. Is there any way to make them even regardless of their values?
I expect to find an option from Highcharts
You can translate your tick positions into a constant interval, calculate data based on the proportion and show mocked labels/tooltips.
For example:
const tickPositions = [40, 60, 80, 100, 160, 220, 280, 340, 400, 460, 520];
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const processedTickPositions = tickPositions.map((tick, index) => index);
const getProcessedData = (data) => {
const foundTick = tickPositions.find(tick => tick > data);
const prevTickIndex = tickPositions.indexOf(foundTick) - 1;
const prevTick = tickPositions[prevTickIndex];
if (!foundTick) {
return processedTickPositions[0];
}
return prevTickIndex + (data - prevTick) / (foundTick - prevTick);
}
const chartOptions = {
series: [{
...,
data: [{
y: getProcessedData(180),
custom: {
value: 180,
unit: "kg",
label: "label"
}
}]
}],
yAxis: [{
...,
labels: {
formatter: function() {
return tickPositions[this.pos]
}
}
}],
...
};
Highcharts.chart('container', chartOptions);
Live demo: http://jsfiddle.net/BlackLabel/yj7akt29/
API Reference: https://api.highcharts.com/highstock/yAxis.labels.formatter

Javascript using for...in loop with objects

Is anyone can help me to found this output.
Sample output:
['milk', 'bread', 'potato']
[20, 15, 10]
Here is the code.
var itemsToBuy = {
milk: {
quantity : 5,
price: 20
},
bread: {
quantity : 2,
price: 15
},
potato: {
quantity : 3,
price: 10
}
}
I have found for first array using Object.keys(itemsToBuy) but not able to found for second array.
User Object.values and map for second array
var itemsToBuy = {
milk: { quantity: 5, price: 20 },
bread: { quantity: 2, price: 15 },
potato: { quantity: 3, price: 10 },
};
const out1 = Object.keys(itemsToBuy);
const out2 = Object.values(itemsToBuy).map(({ price }) => price);
console.log(out1, out2);
// Using for..in loop
const out3 = [];
for(const key in itemsToBuy) {
out3.push(itemsToBuy[key].price)
}
console.log(out3)
Object.values(itemsToBuy).map(item => item.price) should do the trick

How to add ak set of keys + values in dictionaries inside a list inside a dictionary

I'm learning to use ReactJs but I don't understand how I could add a key + value to a set of dictionaries contained in a list itself contained in a dictionary ...?
here are the datas :
export const datasTest = {
labels: ["1", "2", "3", "4", "5", "6"],
datasets: [
{
label: "# of Red Votes",
data: [12, 19, 3, 5, 2, 3],
},
{
label: "# of Blue Votes",
data: [2, 3, 20, 5, 1, 4],
},
{
label: "# of Green Votes",
data: [3, 10, 13, 15, 22, 30],
},
],
};
So i would like to get this :
export const datasTest = {
labels: ["1", "2", "3", "4", "5", "6"],
datasets: [
{
label: "# of Red Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: "#c4b02e",
},
{
label: "# of Blue Votes",
data: [2, 3, 20, 5, 1, 4],
backgroundColor: "#f3bf1d",
},
{
label: "# of Green Votes",
data: [3, 10, 13, 15, 22, 30],
backgroundColor: "#fb601f",
},
],
};
I added 'backgroundColor: "#fb601f"' (by hand :))
with
export const colorForLabel = [
{ label: "# of Red Votes", colour: "#c4b02e" },
{ label: "# of Blue Votes", colour: "#f3bf1d" },
{ label: "# of Green Votes", colour: "#fb601f" },
];
I writted this, but i'm stuck, i don't know how to append my new values :
const [data, setDatas] = useState(
CscDataService.getDatas()
);
function setColor() {
{
Object.entries(data["datasets"]).map(([key, values]) => {
Object.entries(values).map(([key, value]) => {
console.log(key + " " + value);
});
});
}
}
Can you give me a hand ? Thanks
Something like this ?
function setColor() {
const updatedDatasets = data.datasets.map(dataset => {
const { colour } = colorForLabel.find(({ label }) => label === dataset.label) || {};
return {
...dataset,
backgroundColor:colour
}
});
setDatas(currentData => ({
...curentData,
datasets: updatedDatasets
}));
}
};
You can use functional state update to get access to the previous state and add backgroundColor to each object like:
export const colorForLabel = [
{ label: "# of Red Votes", colour: "#c4b02e" },
{ label: "# of Blue Votes", colour: "#f3bf1d" },
{ label: "# of Green Votes", colour: "#fb601f" },
];
function setColor() {
setDatas((prevData) => {
return {
...prevData,
datasets: prevData.datasets.map(dataset => ({...dataset, backgroundColor: colorForLabel.find(({label}) => label === dataset.label).colour}))
}
})
}

How to create a combination of array is react js?

I need to create a combination of arrays.
I have the data like this and I need to arrange the data for the chart series
[
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
and I expected a result like this the following method
[
{
"name":"Moving Duration",
"data":[
10,
15,
43,
67,
47
]
},
{
"name":"Parked Duration",
"data":[
15,
23,
26,
21,
54
]
}
]
Any help would be appreciated. thank you
Run the data through an array reduce to group by property key, then map it to the resultant object format you want.
const formattedData = data.reduce((data, current) => {
Object.entries(current).forEach(([key, value]) => {
data[key] = [...(data[key] ?? []), value];
});
return data;
}, {});
const finalData = Object.entries(formattedData).map(([name, data]) => ({
name,
data
}));
const data = [
{
movingDuration: 10,
parkedDuration: 15
},
{
movingDuration: 15,
parkedDuration: 23
},
{
movingDuration: 43,
parkedDuration: 26
},
{
movingDuration: 67,
parkedDuration: 21
},
{
movingDuration: 47,
parkedDuration: 54
}
];
const formattedData = data.reduce((data, current) => {
Object.entries(current).forEach(([key, value]) => {
data[key] = [...(data[key] ?? []), value];
});
return data;
}, {});
const finalData = Object.entries(formattedData).map(([name, data]) => ({
name,
data
}));
console.log(finalData);
Does this help?
const arr = [
{
movingDuration: 10,
parkedDuration: 15
},
{
movingDuration: 15,
parkedDuration: 23
},
{
movingDuration: 43,
parkedDuration: 26
},
{
movingDuration: 67,
parkedDuration: 21
},
{
movingDuration: 47,
parkedDuration: 54
}
];
const resultArray = [{ name: 'Moving Duration', data: [] }, { name: 'Parked Duration', data: [] }];
arr.forEach((ele) => {
resultArray[0].data.push(ele.movingDuration);
resultArray[1].data.push(ele.parkedDuration);
});
Let me know if this helps.
const origData=[
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
const cols=Object.keys(origData[0])
const result=cols.map(item=>{
const data=origData.map(i=>i[item])
return {name:item,data}
})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
let data = [
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
let sol = {}
data.forEach(d => {
let keys = Object.keys(d);
if(sol[keys[0]]){
sol[keys[0]] = [...sol[keys[0]], d[keys[0]]]
sol[keys[1]] = [...sol[keys[1]], d[keys[1]]]
}else{
sol[keys[0]] = [].concat(d[keys[0]])
sol[keys[1]] = [].concat(d[keys[1]])
}
})
let final = Object.keys(sol).map(key =>{
let temp = {}
temp["name"] = key
temp["data"] = sol[key]
return temp
})
console.log(final)
We can use reduce() method to create an object with Object.values() to get values from object:
const result = data.reduce((a, c) => {
for (const key in c) {
a[key] = a[key] || {name: key, data: []};
a[key].data.push(c[key]);
}
return a;
}, {})
console.log(Object.values(result));
An example:
let data = [
{
"movingDuration":10,
"parkedDuration":15,
},
{
"movingDuration":15,
"parkedDuration":23,
},
{
"movingDuration":43,
"parkedDuration":26,
},
{
"movingDuration":67,
"parkedDuration":21,
},
{
"movingDuration":47,
"parkedDuration":54,
}
]
const result = data.reduce((a, c) => {
for (const key in c) {
a[key] = a[key] || {name: key, data: []};
a[key].data.push(c[key]);
}
return a;
}, {})
console.log(Object.values(result));

Sum array of objects with Lodash

I'd like to sum objects from array, I've been searching and testing different things founds around there, using Lodash or not, without any success.
Here is the data array, there is 5 elements but it could be less or more. The properties will always be the same, but there could be a lot more.
const data = [
{
from: "2019-10-15",
stats: [
{
options: {
width: 15,
height: 20,
borders: 35,
removable: 5
}
}
]
},
{
from: "2019-10-16",
stats: [
{
options: {
width: 22,
height: 18,
borders: 10,
removable: 0
}
}
]
},
{
from: "2019-10-17",
stats: [
{
options: {
width: 0,
height: 15,
borders: 15,
removable: 0
}
}
]
},
{
from: "2019-10-18",
stats: [
{
options: {
width: 20,
height: 20,
borders: 10,
removable: 5,
}
}
]
},
{
from: "2019-10-19",
stats: [
{
options: {
width: 0,
height: 10,
borders: 0,
removable: 30
}
}
]
}
];
The expected result is the sum of each array element stats[0].options properties:
const sum = {
width: 57,
height: 83,
borders: 70,
removable: 40
}
I know it's definitely not complicated.
Use _.map() to get the options, then combine the objects using _.mergeWith(), and use _.add() as the customizer.
const data = [{"from":"2019-10-15","stats":[{"options":{"width":15,"height":20,"borders":35,"removable":5}}]},{"from":"2019-10-16","stats":[{"options":{"width":22,"height":18,"borders":10,"removable":0}}]},{"from":"2019-10-17","stats":[{"options":{"width":0,"height":15,"borders":15,"removable":0}}]},{"from":"2019-10-18","stats":[{"options":{"width":20,"height":20,"borders":10,"removable":5}}]},{"from":"2019-10-19","stats":[{"options":{"width":0,"height":10,"borders":0,"removable":30}}]}];
const result = _.mergeWith({}, ..._.map(data, 'stats[0].options'), _.add);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
If you use lodash/fp you can create a function using _.flow(), and replace _.mergeWith with _.mergeAllWith():
const { flow, map, mergeAllWith, add } = _;
const fn = flow(
map('stats[0].options'),
mergeAllWith(add)
);
const data = [{"from":"2019-10-15","stats":[{"options":{"width":15,"height":20,"borders":35,"removable":5}}]},{"from":"2019-10-16","stats":[{"options":{"width":22,"height":18,"borders":10,"removable":0}}]},{"from":"2019-10-17","stats":[{"options":{"width":0,"height":15,"borders":15,"removable":0}}]},{"from":"2019-10-18","stats":[{"options":{"width":20,"height":20,"borders":10,"removable":5}}]},{"from":"2019-10-19","stats":[{"options":{"width":0,"height":10,"borders":0,"removable":30}}]}];
const result = fn(data);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash#4(lodash.min.js+lodash.fp.min.js)'></script>
It can be done through vanill JavaScript. Just use reduce and foreach methods:
const data = [
{
from: "2019-10-15",
stats: [
{
options: {
width: 15,
height: 20,
borders: 35,
removable: 5
}
}
]
},
{
from: "2019-10-16",
stats: [
{
options: {
width: 22,
height: 18,
borders: 10,
removable: 0
}
}
]
},
{
from: "2019-10-17",
stats: [
{
options: {
width: 0,
height: 15,
borders: 15,
removable: 0
}
}
]
},
{
from: "2019-10-18",
stats: [
{
options: {
width: 20,
height: 20,
borders: 10,
removable: 5,
}
}
]
},
{
from: "2019-10-19",
stats: [
{
options: {
width: 0,
height: 10,
borders: 0,
removable: 30
}
}
]
}
];
const result = data.reduce((a, {stats}) => {
stats.forEach(({options}) => {
for (const key in options) {
a[key] = a[key] || 0;
a[key] += options[key];
}
});
return a;
}, {})
console.log(result);
The vanilla JS code looks like this:
const result = data.reduce((a, {stats}) => {
stats.forEach(({options}) => {
for (const key in options) {
a[key] = a[key] || 0;
a[key] += options[key];
}
});
return a;
}, {})
Another approach to do this with a reduce and nested forEach, but a bit more straightforward:
const data = [
{
from: "2019-10-15",
stats: [
{
options: {
width: 15,
height: 20,
borders: 35,
removable: 5
}
}
]
},
{
from: "2019-10-16",
stats: [
{
options: {
width: 22,
height: 18,
borders: 10,
removable: 0
}
}
]
},
{
from: "2019-10-17",
stats: [
{
options: {
width: 0,
height: 15,
borders: 15,
removable: 0
}
}
]
},
{
from: "2019-10-18",
stats: [
{
options: {
width: 20,
height: 20,
borders: 10,
removable: 5,
}
}
]
},
{
from: "2019-10-19",
stats: [
{
options: {
width: 0,
height: 10,
borders: 0,
removable: 30
}
}
]
}
];
let result = _.reduce(data, (acc, value) =>{
// our nested options object
const options = value.stats[0].options;
_.forEach(options, (optionValue, optionKey) =>{
// if we know about this key already, then add optionValue to it
// if not, this will be our first value for that key
acc[optionKey] = !!acc[optionKey] ? acc[optionKey] + optionValue : optionValue;
})
return acc;
}, {})
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Resources