- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding elements whose successors and predecessors are in array in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.
The function should construct and return a new array that contains all such elements from the original array whose successor and predecessor are both present in the array. If means, if any element num is in the original array, it should be included in the result array if and only if num - 1 and num + 1 are also present in the array.
For example −
If the input array is −
const arr = [4, 6, 8, 1, 9, 7, 5, 12];
Then the output should be −
const output = [ 6, 8, 7, 5 ];
Example
The code for this will be −
const arr = [4, 6, 8, 1, 9, 7, 5, 12]; const pickMiddleElements = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const num = arr[i]; const hasBefore = arr.includes(num - 1); const hasAfter = arr.includes(num + 1); if(hasBefore && hasAfter){ res.push(num); }; }; return res; }; console.log(pickMiddleElements(arr));
Output
And the output in the console will be −
[ 6, 8, 7, 5 ]
- Related Articles
- Finding upper elements in array in JavaScript
- Finding array intersection and including repeating elements in JavaScript
- Finding desired sum of elements in an array in JavaScript
- Finding minimum steps to make array elements equal in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Finding the product of array elements with reduce() in JavaScript
- Finding special kind of elements with in an array in JavaScript
- Finding three elements with required sum in an array in JavaScript
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Finding matches in two elements JavaScript
- Finding two closest elements to a specific number in an array using JavaScript
- How to return an array whose elements are the enumerable property values of an object in JavaScript?
- Finding peculiar pairs in array in JavaScript
- Maximum length of the sub-array whose first and last elements are same in C++
- Finding reversed index of elements in arrays - JavaScript

Advertisements