I have an array that looks like the following and I want to flatten the array with the same value, to produce textual representations of the data.
[
{level: 'red', state: 'very high', key: 'temperature', value: '37.7'},
{level: 'red', state: 'very high', key: 'pH', value: '7.5'},
{level: 'green', state: 'very low', key: 'galvanic', value: '34'}
]
Your temperature, pH is very high. Your galvanic is very low.
I’ve tried flattening and filtering the array as follows.
function textMaker(alert){
let flatArray = alert.reduce((acc, curVal) => {
return acc.concat(curVal.key);
}, []);
return "Your <span>"+flatArray.join(", ")+"</span> is <span>quite high</span>.";
}
const alerts = [
{level: 'red', state: 'very high', key: 'temperature', value: '37.7'},
{level: 'red', state: 'very high', key: 'pH', value: '7.5'},
{level: 'green', state: 'very low', key: 'galvanic', value: '34'}
]
let redAlerts = alerts.filter((item) => item.level === "red");
console.log(textMaker(redAlerts));
4
Answers
you do your textmaker as I understand like the following:
First thing first, group all the objects with the same ‘level’ and ‘state’ then making the text will become an easy task to do
I don’t see flattening here, but you have to group the items first and then map
You can go with below code as well. I’ve handled few exceptions also.