- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Removing least number of elements to convert array into increasing sequence using JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers. Our function should try and remove the least number of elements from the array so that the array becomes an increasing sequence.
Example
Following is the code −
const arr = [1, 100, 2, 3, 100, 4, 5]; const findIncreasingArray = (arr = []) => { const copy = arr.slice(); for(let i = 0; i < copy.length; i++){ const el = arr[i]; const next = arr[i + 1]; if(el > next){ copy[i] = undefined; }; }; return copy.filter(Boolean); }; console.log(findIncreasingArray(arr));
Output
[ 1, 2, 3, 4, 5 ]
Advertisements