I have two arrays array1 and array2 in my Node.js application, both of which may contain duplicate elements. I need to calculate the position change for each element in array1 compared to array2. I know for sure that the arrays are of the same length and contain the same characters. The position change is defined as the difference in index positions between the same element in the two arrays. However, since the arrays may contain duplicates, I cannot use the indexOf method to find the index of each element in array2 or use dictionaries.
const array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'A'];
const array2 = ['A', 'B', 'E', 'C', 'D', 'A' 'F'];
in this example, E had its index moved backwards by 2 positions and A (the second one) and F were swapped.
Here is what I tried after checking some answer here :
function collectPositionChange({
recent,
result
}, value, currentIdx) {
const recentIdx = recent.indexOf(value);
if (recentIdx !== currentIdx) {
// calculate the difference in the indices
const idxDiff = currentIdx - recentIdx;
result.push({
value,
currentIdx,
recentIdx,
idxDiff,
});
// update the recent array
recent.splice(recentIdx, 1); // remove the value from the recent array
recent.splice(currentIdx - (idxDiff > 0 ? 1 : 0), 0, value); // insert the value at its new position
if (idxDiff < -1) {
console.log(`The value '${value}' moved backwards by ${Math.abs(idxDiff)} positions.`);
} else if (idxDiff > 1) {
console.log(`The value '${value}' moved frontwards by ${Math.abs(idxDiff)} positions.`);
} else if (Math.abs(idxDiff) === 1) {
const otherValue = recent[recentIdx];
console.log(`The values '${value}' and '${otherValue}' were swapped.`);
}
}
return {
recent,
result
};
}
const array1 = ['A', 'B', 'E', 'C', 'D', 'A', 'F'];
const array2 = ['B', 'A', 'C', 'D', 'E', 'F', 'A'];
console.log(
array1
.reduce(collectPositionChange, {
recent: array2,
result: []
})
.result
);