Per Ström Per Ström - 9 days ago 5
Javascript Question

Find duplicate position of two arrays, javascript

I have two arrays, one

oldArray
and one
newArray
. They are both flat and have the same length. I want a function that checks if the
newArray
has a duplicate, and I want the position that contains the duplicate compared to in the
oldArray
.

Example:

var oldArr = ['abc', null, 'dd', null, 'cc]
var newArr = ['abc', null, 'dd', 'dd', 'cc]


The
dd
is the duplicate and it happened at position 3 compared to the old array. Is there any smart way to do this? Ok to use underscore/lodash in answer.

Answer

Iterate the newArr using Array#reduce, and store the position of every element, that is found on another index in oldArr:

var oldArr = ['abc', null, 'dd', null, 'cc'];
var newArr = ['abc', null, 'dd', 'dd', 'cc'];

var duplicates = newArr.reduce(function(d, e, i) {
  var oldIndex = oldArr.indexOf(e);
  oldIndex !== -1 && oldIndex !== i && d.push(i);
  
  return d;
}, []);
              
console.log(duplicates);