I have a sorted array that may be missing numbers: example would be [3,4,5,7,8] and I'm going to push the missing number into a separate array. I was trying to use a forEach loop because I'm not returning anything but I need to compare the element in the array to the next element in the array.
I know I could use a For loop and just access it by doing + 1 to the variable so I could get the next index but how does that work with a forEach?
2 Answers
If you want to do this in general, you can compute the gap as you go through and make the array of missing numbers in a reduce() loop. Something like:
let arr = [-2,3,4,5,7,8,10,15]
let missing = arr.reduce((arr, item, index, self) => {
let gap = self[index+1] - item - 1 // will be NaN with index + 1 is out of range
return gap > 0
? arr.concat(Array.from({length: gap}, (_, i) => i+1 + item))
: arr
}, [])
console.log(missing.join(', '))
1 Comment
Mark
Hope it helps @RaymonOpie
As simple as this:
const arr = [3,4,5,7,8];
arr.forEach((item, index, array) => {
const next = array[index + 1];
console.log(next);
});
8 Comments
Nurbol Alpysbayev
@RaymonOpie Thanks Raymon. Yes this is a simple question, but I am ready to answer to very complex ones, but there are no such currently!
Patrick Roberts
@NurbolAlpysbayev since you asked, you've deleted your previously-downvoted answer which 10k+ rep users can see, and posted a duplicate answer to avoid downvotes. This is against the site rules, which is why you now have multiple downvotes.
Nurbol Alpysbayev
@PatrickRoberts And do you know why I deleted it? Because I made a silly mistake there, then almost instantly fixed it, but the downvote was still there so I decided to make a new answer, initially correct one.
Patrick Roberts
That doesn't matter. In its current form, the deleted answer is an exact duplicate of the current answer. It is not your choice to decide whether to duplicate content in order to avoid downvotes of previous revisions. It would have been more appropriate to ask "Why the downvotes?" on your previous answer after editing rather than immediately deleting it. The user might have had time to retract their vote... now they've probably moved on.
Patrick Roberts
|
[3,4,5,7,8]a new array of[6]should be created?forEach().