I am trying to correct the incremented value in the data I received. It looks more or less like this:
const data = [1,2,4,5,6,7];
const correctResult = [1,2,3,4,5,6];
What I would like to get is rightly incremented values + 1 but so as to preserve the possible indexes.
I wrote such a function but it is not efficient:
let array = [1,2,4,5,6,7];
array.map((item, index, array) => {
if (item === array[index + 1] - 1) {
return;
}
array[index + 1] = array[index + 1] - 1;
});
console.log(array)
The programming code is javascript. I would like to write a good code to be a good model for me.
not sure if this is the exact answer you seek, but you can try this too
const data = [1, 2, 4, 5, 6, 7];
const correctResult = data.map((item, index) => {
if (item - 1 !== index) {
return --item;
}
else {
return item;
}
});
console.log(correctResult);