In an array of numbers, I need to find repeating values and replace them with null.
Examples
Replace 6 in the middle of array if its neighbors are also 6
[1, 4, 3, 6, 6, 6, 6, 3, 2] => [1, 4, 3, 6, null, null, 6, 3, 2]
Replace 6 at the end of the array if the penultimate value is 6 :
[2, 6, 6, 6, 5, 2, 6, 6] => [2, 6, null, 6, 5, 2, 6, null]
Replace 6 at the start of the array if the next value is 6
[6, 6, 2, 3, 5, 6] => [null, 6, 2, 3, 5, 6]
Any ideas how to achieve this? I'm open to using lodash / underscore if needed
CodePudding user response:
You have to iterate through the array and check for the cases you mentioned.
- Check if first element is equal to second element
- Check if last element is equal to penultimate element
- Check if element is equal to either neighboring element
The following code should achieve what you asked for.
function replaceRepeats(arr) {
for (let i = 0; i < arr.length; i ) {
if (i === 0) {
if (arr[i] === arr[i 1]) {
arr[i] = null;
}
} else if (i === arr.length - 1) {
if (arr[i] === arr[i - 1]) {
arr[i] = null;
}
} else {
if (arr[i] === arr[i - 1] || arr[i] === arr[i 1]) {
arr[i] = null;
}
}
}
return arr;
}
CodePudding user response:
You could use map
so that you have access to the original array while replacing:
const maskDupes = arr =>
arr.map((val, i, arr) =>
(arr[i-1]??val) == val && (arr[i 1]??val) == val ? null : val
);
console.log(...maskDupes([1, 4, 3, 6, 6, 6, 6, 3, 2]));
console.log(...maskDupes([2, 6, 6, 6, 5, 2, 6, 6]));
console.log(...maskDupes([6, 6, 2, 3, 5, 6]));
Or if the array should be mutated, you could keep track of the current value that must be compared, so you still have it available even when in the array it was replaced by a null:
const maskDupes = arr => {
for (let i = 0, prev = arr[0]; i < arr.length; i ) {
if (prev == arr[i] && arr[i] == (arr[i 1]??prev)) arr[i] = null;
else prev = arr[i];
}
}
let arr = [1, 4, 3, 6, 6, 6, 6, 3, 2];
maskDupes(arr);
console.log(...arr);
arr = [2, 6, 6, 6, 5, 2, 6, 6];
maskDupes(arr);
console.log(...arr);
arr = [6, 6, 2, 3, 5, 6];
maskDupes(arr);
console.log(...arr);