1

I have an array of objects (example):

[
  {
     'Row Labels': '37383783738',
     'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g) 8x120',
  },      
  {
     'Row Labels': '37383783738',
     'ProdCode&Desc': '9HD063 Goodness me! Chargrilled bites (20g) 6x30',
  },      
  {
     'Row Labels': '83322223733',
     'ProdCode&Desc': '39HSH02 MDS Chargrilled Hot & Spicy (40g) 2x30',
  },
  {
     'Row Labels': '83322223733',
     'ProdCode&Desc': '93JSHS Treasured battered fillet (120g) 6x30',
  },
]

How can I loop through each element in array and if the current element's 'Row Label' code matches the next elements 'Row Label' code - then add that ProdCode&Desc to the end of the current elements ProdCode&Desc, with each string being separated by a semi colon.

The expected output of the example above would be:

[
  {
     'Row Labels': '37383783738',
     'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g)8x120; 9HD063 Goodness me! Chargrilled bites (20g) 6x30',
  },           
  {
     'Row Labels': '83322223733',
     'ProdCode&Desc': '39HSH02 MDS Chargrilled Hot & Spicy (40g) 2x30; 93JSHS Treasured battered fillet (120g) 6x30',
  },
]

This is what i have so far:

records.map((record, index, array) => {
   if (record["Row Labels"]
   .toLowerCase()
   .includes(array[index + 1]["Row Lables"].toLowerCase())
) {
   record.push(array[index + 1]["ProdCode&Desc"]);
  }
});

1 Answer 1

1

You could do it using array reduce method.

const data = [
  {
    'Row Labels': '37383783738',
    'ProdCode&Desc': '8H9H89 Homestyle cinnamon cake (200g) 8x120',
  },
  {
    'Row Labels': '37383783738',
    'ProdCode&Desc': '9HD063 Goodness me! Chargrilled bites (20g) 6x30',
  },
  {
    'Row Labels': '83322223733',
    'ProdCode&Desc': '39HSH02 MDS Chargrilled Hot & Spicy (40g) 2x30',
  },
  {
    'Row Labels': '83322223733',
    'ProdCode&Desc': '93JSHS Treasured battered fillet (120g) 6x30',
  },
];

const ret = Object.values(
  data.reduce((prev, c) => {
    const p = prev;
    const key = c['Row Labels'];
    if (!p[key]) p[key] = { ...c };
    else
      p[key] = {
        ...p[key],
        'ProdCode&Desc': (p[key]['ProdCode&Desc'] += `; ${c['ProdCode&Desc']}`),
      };
    return p;
  }, {})
);
console.log(ret);

Sign up to request clarification or add additional context in comments.

3 Comments

Fantastic! Thank you mr hr. I really should take the time to learn .reduce and it's full capabilities.
Is there anyway to return the data in the exact way I stated in my expected output example?
@Perry, Sorry my mistake. I have updated the code. Now check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.