![]() |
To print all the negative numbers in a range from the JavaScript array, we need to iterate over the array and apply the condition to filter out the negative numbers. Once the elements are extracted, we can print them in the console. Example:Input: arr = [-22, 45, 63, -88, -69] Table of Content Using for LoopIn this approach, we are using the for loop to iterate over each element of the array and check if each element is less than 0, which means it is a negative number. Syntax:for (initialization; condition; increment/decrement) { Example: The below code example uses the for loop to print all negative numbers in a range of -60 to -1 in a JavaScript array. Javascript
Output
-1 -4 -55 Using forEach methodIn this approach, we are using the forEach method to iterate over each element of the array to get each of the negative numbers. Syntax:array.forEach(function(currentValue, index, array) { Example: The below code example uses the forEach method to print all negative numbers in a range of -70 to -1 in a JavaScript array. Javascript
Output
-1 -4 -55 -66 Using filter methodIn this approach, we are using the built-in filter method to create the new array which consists of only the negative numbers from the input array. Syntax:const res = array.filter(function(currentValue, index, array) { Example: The below code example uses the filter method to print all negative numbers in a range of -70 to -1 in a JavaScript array. Javascript
Output
[ -1, -4, -55, -66 ] Using for…of LoopIn this approach, we are using the for…of loop to iterative over each element of the input arr and check if the number of the array is less than 0. If the number is less than 0, then it is printed in the console. Syntax:for (variable of iterable) { Example: The below code example uses the for…of Loop to print all negative numbers in a range of -70 to -1 in a JavaScript array. Javascript
Output
-1 -4 -55 -66 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |