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.
{ michael: 2, john: 1 ... }or at least clearly seperate index and username, such asusername#12?