What you can do is iterate over arr2 and save the found index from arr1 in a variable, and if the element arr2 is equal to the previous element in arr2, then compare it with the saved index + 1, for this you can use the 2nd parameter of the indexOf method.
var duplicate =[ 0, 1, 2, 0, 2 ];
var newiter =[ 0, 0, 1, 2, 2 ];
var indexArray = [];
var newiter = newiter.sort();
var i = -1;
for(var j = 0; j<newiter.length; j++) {
if(j > 0 && newiter[j] != newiter[j-1]) {
i = -1;
}
i = duplicate.indexOf(newiter[j], i+1);
indexArray.push(i);
}
console.log(indexArray);
source
share