I have got 2 arrays tags and typenames:

```
const tags = [
    {
        title: 'Warrior',
        data: {
            type: 'audience'
        }
    },
    {
        title: 'Juggler',
        data: {
            type: 'section'
        }
    },
    {
        title: 'Journey',
        data: {
            type: 'audience'
        }
    },
    {
        title: 'Travel',
        data: {
            type: 'nonexistingtag'
        }
    }
];

const typenames = [
    { audience: 'au' },
    { section: 'se' },
    { sponsor: 'sp' },
    { contextual: 'co' }
]

```

The expected output is to create a string that is grouped by keys matching between array1 and array2 type and each key is separated by the pipe "|" symbol and each group is separated by "&" from one another, so for the above sample the final expected output string would be :

```
au=Warrior|au=Journey&se=Juggler

```

Here is what I tried so far,

```
let arr = [];
tags.forEach(element => {
    typenames.forEach(el => {   
        if (Object.keys(el)[0] === element.data.type) // finding matching keys and pushing to an arr
            arr.push({ title: Object.values(el)[0], desc: element.title });
    })
});

```

Sort the keys so that they are easy to group :

```
arr.sort((a, b) => {
    let keya = a.title;
    let keyb = b.title;
    if (keya > keyb) {
        return 1;
    } else if (keya < keyb) {
        return -1;
    } else {
        // the characters are equal.
        return 0;
    }
});

```

Concatenate the string:

```
let str = '';
arr.forEach(({ title, desc }, i, arr2) => {
    if (title === arr2[i + 1]?.title) { // Check that the next item in array has the same title
        str = str.concat(`${title}=${desc}|`)
        return;
    }
    str = str.concat(`&${title}=${desc}`)
});
console.log('str', str);

```

Output :
`au=Warrior|&au=Journey&se=Juggler`

Issues :

1. Since im checking the next item in the array to see if the title matches, then there is an extra unrequired "&"
2. Is there an easier way to accomplish the same ? (Using shorthand, filters etc?)