Why is it when you push a constantly updating object into an array using a for loop, it pushes only the last iteration property values(last updated property values)?
My task was: It is your job to identify every element in an array that isn't sequential.
You should return the results as an array of objects with two values.
I tried this and it didn't work as I expected:
function allNonConsecutive(arr) {
let nonC = {
i: 0,
n: 0,
};
let arrNonC = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] - 1 !== arr[i - 1]) {
nonC.i = arr.indexOf(arr[i]);
nonC.n = arr[i];
arrNonC.push(nonC);
} else continue;
}
return arrNonC;
}
Returns: [{i:7, n:10}, {i:7, n:10}] ❌
Although I solved it like this:
function allNonConsecutive(arr) {
let nonC = {};
let arrNonC = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] - 1 !== arr[i - 1]) {
nonC = {
i: arr.indexOf(arr[i]),
n: arr[i],
};
arrNonC.push(nonC);
} else continue;
}
return arrNonC;
}
Returns: [{i:4, n:6}, {i:7, n:10}] ✔️