0

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
  • 1
    By missing numbers, do you mean given an array of [3,4,5,7,8] a new array of [6] should be created? Commented Dec 21, 2018 at 22:26
  • 1
    Please read the documentation for forEach(). Commented Dec 21, 2018 at 22:26

2 Answers 2

2

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(', '))

Sign up to request clarification or add additional context in comments.

1 Comment

Hope it helps @RaymonOpie
0

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

@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!
@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.
@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.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.