How to use Array Map and Find method In Javascript
In this approach, we are using the forEach method that is iterating over the input along with the element’s index value. find method is used to search for the smaller element by specifying the condition to the right by slicing the array from the current index + 1. When the smaller element is for, ut is pushed on the ouputElements array else, the -1 value is been pushed.
Example: This example implements the above mentioned approach
Javascript
function nextSmall(inputArray) { // let inputArrayLength = inputArray.length; let outputElements = []; inputArray.forEach((element, index) => { let smallerElement = inputArray.slice(index + 1) .find((e) => e < element); outputElements.push(smallerElement || -1); }); return outputElements.join( " " ); } let inputArr1 = [11, 13, 21, 3]; let inputArr2 = [1, 2, 3, 4]; console.log(nextSmall(inputArr1)); console.log(nextSmall(inputArr2)); |
3 3 3 -1 -1 -1 -1 -1
JavaScript Program to Find Next Smaller Element
In this JavaScript article, we will see how we can find the next smaller elements from the first input Array. We have given the array in which we need to print the next smaller element. The next smaller element is an element that is present after the target element in the input array. For elements for which no next smaller elements are present then the -1 will be printed.
Examples:
Input: inputArray=[ 11, 13, 21, 3 ]
Output: 3 3 3 -1
Explanation:
For the rightmost element (3), the next smaller is always -1 since there are no elements to its right.
Element: 3 => -1
Now, let's find the ISE for each element:
Element: 11: The next smaller element to its right is 3.
Element: 13: The next smaller element to its right is 3.
Element: 21: The next smaller element to its right is 3.
Element: 3: The rightmost element, so ISE is -1.
For printing the next Smaller Element we have four different approaches in JavaScript language. We have mentioned these approaches below:
- Using Dynamic Programming Approach
- Using the Stack Data Structure approach
- Using the Reverse Iteration of the Elements approach
- Using the Array Map and Find approach