Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I return the next item in an array with find()?

I am trying to return the next item in the array, that is the element that is next in the index so if I use 7 as an example a below I need to return 8.

nums = [5, 3, 7, 8, 1, 10];
num = 7;

const result = nums.find(number =>{
    if(num === number)  // how do I return index+1 here?
      
});

so for this example I need to return 8 as this is the next item after 7. Is this possible to do with find?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use indexOf

nums = [5, 3, 7, 8, 1, 10];
num = 7;

const indexOfNum = nums.indexOf(num);
const result = nums[indexOfNum + 1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading