Question: I can check if the objects of an array are also present in another array (and display the duplicates in its own array) with the following code:

```
var target = ['alfredo', 'john', 'sebas', 'paul', 'lionel', 'sebas2'];
var src = ['paul', 'michael', 'sebas'];

var final = target.filter(function(val) {
  return src.indexOf(val) != -1;
});

console.log(final);

```

**Desired Output:**

However, I do not know how to get following output:

> 
> final = Array ["paul2", "michael", "sebas3"]
> 
> 
> 

Objects in array `final` should have the same order as originally in array `src` but, if the object is also to be found in array `target` a number (starting from 2) should be attached to this duplicated object. In case the `name + number` exists, the number has to increase by 1 until the value is not found in `target`

My try so far:

```
var final= [];

src.forEach(function(element) {
  if(target.includes(element))
    { newSrc = element+2; final.push(newSrc) } else { final.push(element) }
});

console.log(final);

```

However, I do not know how to deal with the `number + 1` part without recurring to loops in loops etc.

Answer: 
You could count first and then map the names with the adjusted count.

```js
var target = ['alfredo', 'john', 'sebas', 'paul', 'lionel', 'sebas2'],
    src = ['paul', 'michael', 'sebas'],
    count = target.reduce((c, s) => (k => (c[k] = (c[k] || 0) + 1, c))(s.match(/^\D+/)[0]), Object.create(null)),
    final = src.map(s => s + (count[s] ? count[s] + 1 : ''));

console.log(final);
```
An alternative is using the function `reduce` to group the names and the function `some` to check for strings `str + number`. This grouping process creates an object to leverage the fast access using keys.

After that grouping process, get the keys for building the desired output.

```js
var target = ['alfredo', 'john', 'sebas', 'paul', 'lionel', 'sebas2'],
  src = ['paul', 'michael', 'sebas'],
  obj = src.reduce((a, str) => {
    if (target.some(s => str === s))  {
      a[str] = (a[str] || 1) + 1
      while (target.some(s => `${str}${a[str]}` === s)) a[str]++;
    } else a[str] = 0;

    return a;
  }, {}),
  result = Object.keys(obj).map(k => `${k}${obj[k] || '' }`);

console.log(result);
```

```css
.as-console-wrapper {  max-height: 100% !important;top: 0;}
```