skip to Main Content

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


  1. you do your textmaker as I understand like the following:

    function textMaker(alerts) {
      const filteredAlerts = alerts.filter((alert) => alert.level === "red" && alert.state === "very high");
      const keys = filteredAlerts.map((alert) => alert.key);
      if (keys.length > 0) {
        const joinedKeys = keys.join(", ");
        return `Your ${joinedKeys} is at a very high level.`;
      } else {
        return "No alerts matching the specified criteria were found.";
      }
    }
    
    Login or Signup to reply.
  2. First thing first, group all the objects with the same ‘level’ and ‘state’ then making the text will become an easy task to do

    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' },
    ];
    
    const data1 = [
      { level: 'red', state: 'normal', key: 'temperature', value: '37.7' },
      { level: 'red', state: 'very high', key: 'pH', value: '7.5' },
      { level: 'green', state: 'very low', key: 'galvanic', value: '34' },
      { level: 'green', state: 'very low', key: 'suger-level', value: '34' },
    ];
    
    function generateSentence(data){
    const groupedData = {};
    data.forEach(item => {
      const { level, state, key, value } = item;
      if (!groupedData[level]) {
        groupedData[level] = {};
      }
      if (!groupedData[level][state]) {
        groupedData[level][state] = [];
      }
      groupedData[level][state].push(`${key}`);
    });
    
    // Generate the textual representation
    const result = [];
    for (const level in groupedData) {
      for (const state in groupedData[level]) {
        const measurements = groupedData[level][state].join(', ');
        result.push(`Your ${measurements} is ${state}.`);
      }
    }
    
    const finalOutput = result.join(' ');
    
    return finalOutput
    }
    
    console.log(generateSentence(data))
    console.log(generateSentence(data1))
    Login or Signup to reply.
  3. 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))
    Login or Signup to reply.
  4. You can go with below code as well. I’ve handled few exceptions also.

    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'}
    ];
    function textMaker(alert){
      let flatArray = alert.reduce((acc, curVal) => {
        if(acc[curVal["state"]]) acc[curVal["state"]].push(curVal["key"])
        else acc = {...acc, [curVal["state"]]: [curVal["key"]] }
        return acc;
      }, {});
      
      return Object.keys(flatArray).map((key) => `Your ${flatArray[key].join(", ")} is ${key}.`).join(" ")
    }
    
    console.log(textMaker(alerts));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search