Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript flatten array by same value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));

>Solution :

I don’t see flattening here, but you have to group the items first and then map

const 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" },
];

function textMaker(data) {
  const grouped = data.reduce((groups, current) => {
    if (!(current.state in groups)) {
      groups[current.state] = [];
    }
    groups[current.state].push(current);
    return groups
  }, {});
  

  return Object.entries(grouped)
    .map(
      ([state, group]) =>
        `Your ${group.map((item) => item.key).join(", ")} is ${state}.`,
    )
    .join(" ");
}

console.log(textMaker(data))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading